Is It Better to Create a Singleton to Access Unity Container or Pass It Through the Application

Is it better to create a singleton to access unity container or pass it through the application?

The correct approach to DI is to use Constructor Injection or another DI pattern (but Constructor Injection is the most common) to inject the dependencies into the consumer, irrespective of DI Container.

In your example, it looks like you require the dependencies TestSuite and TestCase, so your TestSuiteParser class should statically announce that it requires these dependencies by asking for them through its (only) constructor:

public class TestSuiteParser
{
private readonly TestSuite testSuite;
private readonly TestCase testCase;

public TestSuiteParser(TestSuite testSuite, TestCase testCase)
{
if(testSuite == null)
{
throw new ArgumentNullException(testSuite);
}
if(testCase == null)
{
throw new ArgumentNullException(testCase);
}

this.testSuite = testSuite;
this.testCase = testCase;
}

// ...
}

Notice how the combination of the readonly keyword and the Guard Clause protects the class' invariants, ensuring that the dependencies will be available to any successfully created instance of TestSuiteParser.

You can now implement the Parse method like this:

public TestSuite Parse(XPathNavigator someXml) 
{
List<XPathNavigator> aListOfNodes = DoSomeThingToGetNodes(someXml)

foreach (XPathNavigator blah in aListOfNodes)
{
this.testSuite.TestCase.Add(this.testCase);
}
}

(however, I suspect that there may be more than one TestCase involved, in which case you may want to inject an Abstract Factory instead of a single TestCase.)

From your Composition Root, you can configure Unity (or any other container):

container.RegisterType<TestSuite, ConcreteTestSuite>();
container.RegisterType<TestCase, ConcreteTestCase>();
container.RegisterType<TestSuiteParser>();

var parser = container.Resolve<TestSuiteParser>();

When the container resolves TestSuiteParser, it understands the Constructor Injection pattern, so it Auto-Wires the instance with all its required dependencies.

Creating a Singleton container or passing the container around are just two variations of the Service Locator anti-pattern, so I wouldn't recommend that.

Good or bad Unity design: Injecting the complete container or only explicit Interfaces?

In the first approach, you've got a dependency on the interfaces you need, plus you're adding another one to the container:

var x = this._container.Resolve<IXInterface>();
var y = this._container.Resolve<IYInterface>();

So you've gone against one of the main reasons for DI in the first place.

Should C# Unity Factory be Singleton?

When you're using DI, Singletons are almost never necessary.

Instead I would compose everything at the Composition Root and use appropriate lifetime management with Unity to create the equivalent of Singletons.

Do I pass singletons as parameters or do I manually resolve them? (Unity DI)

Each object that needs its dependencies resolved can potentially have them resolved by the container. To not to spoil your code with containers, you create local factories and implement specific factory providers elsewhere, in the Composition Root which is the only place in your application where container is created and used directly.

This requires discipline, however you are able to structure your code so that there is no explicit reference to the container except for the Composition Root and still container does the job.

I wrote a tutorial on that once, it is too long to quote it here:

http://www.wiktorzychla.com/2012/12/di-factories-and-composition-root.html

Answering your specific question: to have singletons you just use the ContainerControllerLifetimeManager as the parameter to the register method.

http://msdn.microsoft.com/en-us/library/ff660872(v=pandp.20).aspx

Should I be passing a Unity Container in to my dependencies?

You definitely do not want to be passing around containers. You should look into the Unity factory support which will work in this situation. Something like this:

container.RegisterType<IFooBuilder, FrobBuilder>("Frob")
.RegisterType<IFooBuilder, WidgetBuilder>("Widget")
.RegisterType<Func<string, IFooBuilder>>(new InjectionFactory(c => new Func<string, IFooBuilder>(barName => c.Resolve<IFooBuilder>(barName))))

and then ClassC would have a constructor parameter of Func:

public class ClassC : IClassC
{
private readonly Func<string, IFooBuilder> _builderFactory;

public ClassC(Func<string, IFooBuilder> builderFactory)
{
_builderFactory = builderFactory;
}

public ResultObject BuildMyFoo(InitialObject bar)
{
IFooBuilder builder = _builderFactory(bar.Name);
return builder.build(bar);
}
}

Using Unity to create a singleton that is used in my Class

Have you tried this?

container.RegisterType<IMyClass, MyClass>(new ContainerControlledLifetimeManager());

https://msdn.microsoft.com/en-us/library/ff647854.aspx

Since there will be only one instance of your class, there will also one only one instance of HTTP client inside it.

Update:

In order to resolve HttpClient dependency itself, use

container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());

That way any class that needs HttpClient will receive the same instance of it. I'm not sure about the order of parameters, but basically you have to tell Unity 2 things - to register HttpClient as a singleton and to use its default constructor.

Is it good practice to inject IUnityContainer into controller class to save extra code

I'd say that this is not a good idea because it hurts code maintainability. You are creating a strong coupling of your classes to the dependency injection engine, what if you decide in the future that you want to stop using Unity and (for example) switch to Autofac? It also hurts code readability, because it's not obvious what the class dependencies are.

So the proper way to go is either:

  1. Pass the dependencies in the class constructor. It may seem a hassle at first, but it leads to more readable and maintainable code, and you should always favor code readability over your own write time convencience. Moreover, if you find yourself passing too much parameters in the constructor perhaps it's time to review your design (is your controller doing too much? Perhaps it should depend on a business class instead of directly depending on the four repositories...?)

  2. At the very least, if you still want to pass the dependency resolver to your classes, create an abstraction of the dependency resolver so that you are isolated from the concrete engine used. Something like this should be good enough to start with:

.

interface IDependencyResolver
{
T Resolve<T>();
}

You can then create and register an implementation of the class for Unity, which will be easily replaceable if ever needed.

IoC container - singleton or passed around instance?

Neither: both of those approaches hide your dependencies and make your classes hard to use. Instead, Foo should require an IBar in its constructor:

class Foo {
private bar;
public Foo(IBar bar) { this.bar = bar; }
private void DoBarStuff() {
this.bar.DoStuff();
}
}

The only things that should know about your container are your application entry points.

See Dependency Injection Myth: Reference Passing and Service Locator is an Anti-Pattern for additional in-depth discussion.



Related Topics



Leave a reply



Submit