Singleton Unity Container - c#

I just started getting my head around IOC unity framework. I read couple of articles and videos on MSDN. I have good understanding of how this unity thing works.
1.Create container.
2.Register your interface/classes.
3.Resolve your classes.
I think Steps 1,2 should be abstracted for each project. Is it good idea to create singleton class that creates container and registers interfaces/classes so that unity container will be available in entire project for me to resolve. Please advice.

Except for perhaps a few rare circumstances, you should always have a single container instance for your whole application (app domain). DI containers are thread-safe and are optimized for that scenario. Having multiple containers can cause performance problems and can cause maintenance issues, because some scenarios are very hard to achieve (like having application scoped objects for instance).

Use a singleton. In my current company we are using a singleton wrapper around the Unity container that:
is of course singleton
exposes the most important functionality (like registering and resolve)
takes its configuration from web.config/app.config
but can also be fed at runtime (for instance, for unit testing)
has functionality for default handling in case of unexpected errors during resolve
It works like a charm and makes it easy to focus on the important things.

Don't use a singleton. It encourages you to call resolve all over the place, which is a well-known DI antipattern.
Instead, have a single point in your app (the main function in a desktop app, in the app start function in your web app) where you use the container to resolve your object graph and go from there.
Look at Mark Seeman's discussion of "Composition Root" for more details.

Related

Downsides of using two IoC containers in same solution in .NET?

I am working on a project which uses a set of libraries from some other developer which uses structuremap as the IoC container. [I have the codebase with me]
The application in which we are incorporating these libraries uses unity container.
Is there a downside to having two container frameworks in the same solution? I want to move everything over to the same IoC container but how do I justify the extra effort?
There is a difference between having multiple container libraries in the same solution vs. the same application, since a solution can consist of multiple runnable applications.
All components should be wired in the application's start-up path, a.k.a. the Composition Root:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
Together with the use of Constructor Injection, the Composition Root pattern keeps your application completely loosely coupled, and keeps your application code decoupled from your DI Container.
According to the Composition Root pattern, no other parts of an application should therefore depend on a DI Container. The fact that the libraries that you use do, is problematic, because this forces you into a certain DI Container. A better solution is to make the libraries DI-friendly.
There are a few downsides to having multiple container libraries in the same solution:
You have to learn two different DI Container libraries, each with their limitations and quirks
Each library comes with its own risk to needing to be replaced when development stops.
On top of that, there are a few downsides to using multiple container libraries in the same application:
Complexities can arise when a single object graph is constructed of application components that come from different containers. It can be hard to visualize object graphs and verify them for correctness.
If some component is resolved from both containers, it could lead to Torn Lifestyles
That's not to say that you should never have multiple containers in the same solution or application. For instance, you could have two containers as a temporary solution, because you are moving from one library to the next, but a big bang migration is too much work. Ideally, you would in that case migrate one application at the time, but even that could be too much to chew off at once.
Another common scenario where having two containers is fine, is when the application framework you are running is using a DI Container internally to build up its services. Common examples of these frameworks are ASP.NET Core and NServiceBus. In that case, to make the distinction clear, I typically talk about the framework's configuration system instead of its internal container, since that's what it basically is. It being a container, is an implementation detail.
In that case you can leave the built-in 'configuration system' as-is to resolve framework components, and use your DI Container of choice to build object graphs of application components.

mvc - reusing service behavior

I have been working on a MVC-EF application. We use DI container to inject dependencies into controllers, services, and repositories i.e across the UI-Services-DataAccess layers.
My question is regarding DI in services. One thing I have been confused about recently has been arisen from the need to use the behaviour (aka methods) that was implemented in one service in another service.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
So my question is, how should I work this out?
Should I be implementing the needed behaviour in second service (as part of its own methods) or I can somehow reuse it from the already implemented first service?
Can DI container help me in this regard?
Or is it that the way out is to outsource behaviour implemented in services into a separate Business Logic Layer, so it is available to each of the services? BTW, we currently do not have a separate BLL.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
This isn't quite true. In general, your objects refer to each other, forming a graph. When we discuss Dependency Injection, we normally call it a Dependency Graph.
As long as this graph is a Directed Acyclic Graph, all is good. The keyword here is acyclic, but it doesn't preclude reuse. You can have several services that use a single instance of another service; that just means that the service is shared.
Dependency Graphs can be as shallow or as deep as required, as long as they are acyclic, you can compose dependency graphs with confidence.
As usual the answer is, "It depends", however based on what you have said regarding needing some behavior/method to be available to multiple services, I think the last approach you mentioned makes the most sense.
Creating an independent class for "Support" functions can be useful in a lot of scenarios, particularly if you have methods that are a used for several services. DI should then be able to help you provide the "Support" class to its dependents.

How to use dependency injection in enterprise projects

Imagine you have an application with several hundreds of classes implementing dozens of "high level" interfaces (meaning component level). Is there a recommend way of doing dependecy injection (like with unity). Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton? Should a container be passed around, where all instances can RegisterInstance? Should everything be done by RegisterType somewhere in the startup? How can the container be made accessible when needed. Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern.
And: having a container "available" may bring developers to the idea of resolving server components in client context. how to avoid that?
Any discussion welcome!
edit for clarification
I figured out a somewhat realworld example to have a better picture of what problems i see.
lets imagine the application is a hifi system.
the system has cd player (integrated in a cd-rack) and
an usb port (integrated in an usb rack) to play music from.
now, the cd player and the usb port shall be able to play mp3 music.
i have an mp3 decoder somewhere around, which is injectable.
now i start the hifi system. there is no cd inserted yet and
no usb stick pluged in. i do not need a mp3 decoder now.
but with constructor injection, i have to already inject
the dependency into the cd rack and the usb rack.
what if i never insert a mp3 cd or an mp3 usb stick?
shall i hold an reference in the cd rack, so when an mp3 cd
is inserted, i have a decorder on hand? (seems wrong to me)
the decoder is needed in a subsystem of the cd rack, which
is only started if a mp3 gets inserted. now i have no container
in the cd rack, what about constructor injection here?
First of all, Dependency Injection is a design pattern that does not require a container. The DI pattern states:
Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time
Take for example Guice (java dependency injection framework), in Java Guice is a DI framework but it is not a container itself.
Most of the DI tools in .Net are actually containers, so you need to populate the container in order to be able to inject the dependency
I do not like the idea to have to register every component every time in a container, I simply hate that. There are several tools that help you auto register components based on conventions, I do not use Unity, but I can point you for example to Ninject or AutoFac
I am actually writing a small utility to auto register components based on conventions using practically any DI tool, it is still in dev phase
About your questions:
Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton?
The answer is yes, (there's a tool to abstract the DI tool used, it is called ServiceLocator) that's how DI tools work, there is a static container available to the application, however, it is not recommended to use it inside the domain objects to create instances, that's considered an anti-pattern
BTW I have found this tool really useful to register components at runtime:
http://bootstrapper.codeplex.com/
Should a container be passed around, where all instances can RegisterInstance?
No. that would violate the law of Demeter. If you decide to use a container is better to register the components when the application starts
How can the container be made accessible when needed
Well using the Common Service Locator you could use it anywhere in your application, but like I said, it is not recommended to use it inside the domain objects to create the required instances, instead, inject the objects in the constructor of the object and let the DI tool to automatically inject the correct instance.
Now based on this:
Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern
Makes me think that you are not writing unit tests heavily for your application which is bad. So my suggestion is, before choosing between which DI tool you are going to use, or before taking all the answers you get to this question into consideration, refer to the following links which are focus on one thing: Write clean testable code, this is by far the best source you could get to answer yourself your own question
Clean Code talks:
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
Articles
http://misko.hevery.com/2010/05/26/do-it-yourself-dependency-injection/
http://misko.hevery.com/code-reviewers-guide/
Previous link in PDF http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
The following links are super highly recommended
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
http://www.loosecouplings.com/2011/01/how-to-write-testable-code-overview.html
First, there is the Composition Root pattern, you set up your dependencies as soon as possible, Main() in desktop, global.asax/app_start in web. Then, rely on constructor injection as this makes your dependencies clear.
However, you still need something to actually RESOLVE dependencies. There are at least two approaches known to me.
First one consist in using the Service Locator (which is almost equal to making the container a singleton). This is considered an antipattern for a lot of people, however it just works great. Whenever you need a service, you ask your container for it:
... business code...
var service = ServiceLocator.Current.GetInstance<IMyService>();
service.Foo();
Service Locator just uses a container you set up in the Composition Root.
Another approach consist in relying on object factories available as singletons with the container injected into them:
var service = IMyServiceFactory.Instance.CreateService();
The trick is that implementation of the factory uses the container internally to resolve the service. However, this approach, with an additional factory layer, makes your business code independent and unaware of the IoC! You are free to completely redesign the factories to not to use IoC internally and still maintain every single line of business code.
In other words, it's just a trick then to hide the container/locator behind a factory layer.
While tempted to use the former approach (rely directly on the locator) I prefer the latter. It just feels cleaner.
I wonder if there are other viable alternatives here.
Should a container be passed around
No, since this leads to the Service Locator anti-pattern.
where all instances can RegisterInstance
Services should be registered in the start-up path of the application, not by types themselves. When you have multiple applications (such as web app, web service, WPF client), there will often be a common bootstrapper project that wires all services together for shared layers (but each application will still have its unique wiring, since no application behaves the same).
Should everything be done by RegisterType somewhere in the startup
Yes, you should wire everything up at start-up.
How can the container be made accessible when needed.
You shouldn't. The application should be oblivious to the use of a container (if any container is used, since this is optional). If you don't do this, you will make a lot of things much harder, such as testing. You can however, inject the container in types that are defined in the startup path of the application (a.k.a. the Composition Root). This way the application keeps clean from knowing anything about the container.
Constructor injection seems false, controverse of being the standard way
Constructor injection is the prefered way of injecting dependencies. However, it can be challanging to refactor an existing application towards constructor injection. In **rare* circumstances where constructor injection doesn't work, you can revert to property injection, or when it is impossible to build up the complete object graph, you can inject a factory. When the factory implementation is part of the composition root, you can let it depend on the container.
A pattern I found very useful, that can be built on top of the Dependency Injection pattern and the SOLID design principles, is the command / handler pattern. I found this a useful pattern in smaller apps, but it will shine when applications get big, such as enterprise applications.
now i start the hifi system. there is no cd inserted yet and no usb
stick pluged in. i do not need a mp3 decoder now.
This seems like a perfect fit for Setter injection (=property injection in C#). Use a NeutralDecoder or NullDecoder as a default and inject an Mp3Decoder when you need it. You can do it by hand or using a DI container and conditional/late binding.
http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
We usually advise people to use constructor injection for all
mandatory collaborators and setter injection for all other properties.

Instantiate service layer and repositories once during life of web application

During the life of my web application I know all of my services and repositories will be called. I would like to instantiate them once during the startup of the web application and refer to the instantiated references in my code.
Is there a common pattern for instantiating your services/repositories only once during the lifetime of a web application without making them static or singletons.
I would like to avoid making my services/repositories static classes or singletons for testability however instantiating them on every web request doesn't seem right when they are designed to be stateless and I know they will all be needed during the lifetime of the application.
I am using c#/asp.net.
The concept you need is called IoC / DI, and there are many frameworks for this. When you have a class like CustomerService and you need a CustomerRepository in it, by definition that is a dependancy, and you should pass it through the constructor of CustomerService - but then there is the question where you will instantiate CustomerService? Well, who uses that service should get it through constuctor too, it is maybe a CustomerPresenter, or some other class, irrelevant. My point is that with doing dependancy injections you structure your code to a very single point where an IoC / DI framework resolves those dependancies accoring to your rules.
At the very top of the program, you would have something like:
ICustomerPresenter presenter = IoC.Resolve<ICustomerPresenter>();
and everything will automatically come together behind the scenes.
To achieve this, here is an example with StructureMap:
For<ICustomerPresenter>().Use<CustomerPresenter>();
For<ICustomerService>().Singleton().Use<CustomerService();
For<ICustomerRepository>().Singleton().Use<CustomerRepository>();
With this, you keep the testability. I've simplified things a lot here, so this isn't much usable as-is, but there are plenty IoC / DI resources online, so check them out.
Note: for web applications you will want to check out handling lifecycle per request, you will rarely have singletons for entire web application.
Dependency Injection frameworks will take care of the lifetime of your objects.
Eg
container.RegisterType<MyService>().Singleton();
There are many DI frameworks choose what suits you best.

What is the overhead cost associated with IoC containers like StructureMap?

After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. StructureMap in particular uses both attributes and bootstrapper concepts to map requests for IThing to ConcreteThing. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for StructureMap or other IoC tools) and what the associated overhead might be either at run-time or compile-time?
I can't say much for other IoC toolkits but I use Spring.Net and have found that there is a one off initial performance penalty at startup. Once the container has been configured the application runs unaffected.
I use Windsor from the CastleProject and have found it immensely useful in reducing dependencies. I haven't noticed a performance issue yet but one thing I do find is that the configuration can get a bit cumbersome. To help in this regard I'm starting to look at Binsor, which is a DSL for Windsor written in boo.
Another thing to be aware of is that when navigating code you wont be able to go to the code that will be executing at runtime.
They major problem is that code becomes hard to understand. It might become pure magical if one overuse IoC. Another problem is performance. In most cases performance lost is not noticeable. But when you start creating most of your objects via IoC container, it can suddenly drop below ocean level.
I built a very lightweight and basic IOC, here:
http://blogs.microsoft.co.il/blogs/shay/archive/2008/09/30/building-custom-object-mapper.aspx
It's not an alternative to the libraries You mentioned but if all that You need is to resolve a type by giving its interface it might be a perfect solution.
I don't handle instantiation types (singleton, transient, thread, pool...), all object will be instantiated as singletons, you call it like:
IRepository _repository = ObjectFactory.BuildFactory<IRepository>();
Shay

Categories

Resources