Dependency injection: by hand vs autofac - c#

Managing Dependency Injection in C# with Autofac explains in a very concise way with downloadable source code
Dependency injection by hand
var di = new EmployeeObserver(employees, new Printer(Console.Out));
di.FindExperts();
with autofac:
ContainerBuilder autofac = new ContainerBuilder();
autofac.Register(o => new EmployeeObserver(o.Resolve<IList<Employee>>(), o.Resolve<IPrinter>()));
autofac.RegisterType<Printer>().As<IPrinter>();
autofac.RegisterInstance(employees).As<IList<Employee>>();
autofac.RegisterInstance(Console.Out).As<TextWriter>();
using (var container = autofac.Build())
{
container.Resolve<EmployeeObserver>().FindExperts();
}
In some other Q&As, it says we can see the advantage usage of autofac while writing unit test.
Apart from that, could someone give reasons or details more why should I use more complicate code with autofac instead of by manual dependency injection?
It says:
May be on this particular example it's hard to see why this approach
is better than configuring dependency injection by hand, but you
should notice one important thing - with Autofac each component is
configured independently of all the others, and this is what will make
a big difference when your application become more complex.
Can you point an example of complex version of this case, that shows advantage of autofac usage vs dependency by hand that I will stuck with?

Using or not using a DI container has no effect on unit testing. When you unit test, you don't use a DI container because unit tests usually deal with a single or a few classes that you can wire together easily.
Please note that whether to use or not use a DI container to compose your objects is still a highly opinionated question. Here I provide a perspective that I have based on my experience using dependency injection in my projects.
In an article of mine, Why DI containers fail with “complex” object graphs, I define the concept of a simple object graph like this:
An object graph of any size and any depth that has the following two attributes:
a) For any interface (or abstraction) at most one class that implements such interface is used in the object graph.
b) For any class, at most one instance is used in the object graph (or multiple instances with the exact same construction parameter arguments). This single instance can be used multiple times in the graph.
When you have a simple object graph, use a DI container.
For an example of a simple object graph, consider that you have 20 service interfaces that is each implemented by a single class. E.g. IEmailService is only implemented by EmailService, and ISMSService is only implemented by SMSService, etc., and that you have 30 ASP.NET controllers each depending on any number of these service interfaces. Also some of the services depend on other service interfaces, e.g. OrderService depends on IEmailService.
When you don't have a simple object graph, i.e., you have a complex object graph (which is the case for most large applications that apply the SOLID principles), don't use a DI container and instead use Pure DI.
If you use a DI container with a complex object graph, you will end up using complex features of the container like named registrations to distinguish between different implementations of the same interface or between objects that take different construction parameters. This will make your composition root hard to maintain.
You might want to a look at this article of mine about how Pure DI can make your composition root clean.

In some other Q&As, it says we can see the advantage usage of autofac while writing unit test
You've missed the point.
The ability to mock dependency, and, hence, to write unit test, is the advantage of dependency injection as a pattern itself.
Advantage of any DI-container (not only Autofac) is ability to configure dependencies somehow and use this configuration in complex scenarios.
Imagine, that you have some class, that depends on some service, which, in turn depends on some other service, and so on.
It is hard to implement this using poor man's DI, but DI-containers can deal with this.

Related

IoC Instantiate latest time possible

In my application I have many services with I use the following pattern:
In the same file as the interface I define a static factory method which is controlled by the IoC container as follows:
public interface ISomethingService {
Task DoSomethingAsync(int id);
}
public class SomethingServicFactory : ServiceFactory<ISomethingService > { }
public class ServiceFactory<T>
{
public static Func<T> CreateClosure;
public T GetDefault() => CreateClosure();
}
After creating and configuring the IoC container:
SomethingServicFactory .CreateClosure = () =>
Container.GetInstance<ISomethingService >();
Later in my application when I need a SomethingService:
var somethingService= new SomethingService().GetDefault();
This allows me to defer creation until the last moment yet still control the service creation using the container. I just started using SimpleInjector.
More importantly it allows me to create an instance of the service and easily pass it parameters while giving control to the IoC.
A great example where this pattern helps me is in a WPF XAML instantiated user control that needs to populate data (i.e. lookup values from a database). In the code behind I am able to easily create a DbContext and get data from the database. However, I have come to use it throughout the application as well.
I am concerned that I am missing a significant design/architecture problem by using this pattern and I am looking for comments on this pattern by IoC experts.
Your design exposes the following code smells and anti-patterns:
Temporal Coupling: Your CreateClosure property forces you to initialize your service factory after its creation. When you forget this, the application will fail at runtime. Temporal Coupling is a code smell.
Ambient Context: The CreateClosure acts as an Ambient Context (which is much like the Singleton design pattern, but with the ability to change the value using a static method or property). This causes a class's dependencies to be hidden, instead of 'statically declared' using the class's constructor. In Dependency Injection in .NET 2nd edition, we consider Ambient Context an anti-pattern (see chapter 5).
Dependency Inversion Principle violation: Your factories are concrete classes, while the DIP promotes talking to interfaces. As a result, your code becomes strongly coupled and hard to test.
Abstract Factories are a code smell: When applying Dependency Injection, the usefulness of factories evaporates. Especially the idea of having a factory for every abstraction in your application is an absolute no-no.
Instead, with Dependency Injection, everything becomes much easier: When we apply Constructor Injection, we can simply inject ISomethingService into its consumers. This:
Makes it clear what dependencies a class has, by looking at the constructor
Allows the DI container to compose the object graph for you and do analysis and diagnostics on the graph
Allows the container to manage lifetime of objects
Removes the need for having factories (since the container will take that role)
Reduces the number of dependencies a class has. Instead of needing 2 (one for the factory and one for the service), you only need one (for the service).

Should a dependency be injected many "levels" up than it is needed?

I'm writing a C# ASP.NET MVC web application using SOLID principles.
I've written a ViewModelService, which depends on a AccountService and a RepositoryService, so I've injected those two services in the the ViewModelServer.
The PermissionService depends on the HttpContextBase in order to use GetOwinContext() to get an instance of the UserManager. The controller has an instance of HttpContextBase that needs to be used - so it seems like I have to inject the HttpContextBase instance into the ViewModelService which then injects it into the PermissionService.
So, in terms of code I have:
public ViewModelService
public CategoryRepository(ApplicationDbContext context, IPermissionService permissionservice)
public AccountService(HttpContextBase httpcontext, IPrincipal securityprincipal)
to instantiate the ViewModelService, I then do this:
new ViewModelService(
new CategoryRepository(
new ApplicationDbContext(),
new PermissionService(
new AccountService(HttpContext, Thread.CurrentPrincipal),
new UserPasswordRepository(new ApplicationDbContext()),
new ApplicationSettingsService())),
new PasswordRepository(
new ApplicationDbContext(),
new PermissionService(
new AccountService(HttpContext, Thread.CurrentPrincipal),
new UserPasswordRepository(new ApplicationDbContext()),
new ApplicationSettingsService())),
new ModelValidatorService());
Should a dependency be injected from that many "levels" up, or is there a better way?
There's a balance to be struck.
On the one hand, you have the school of thought which would insist that all dependencies must be exposed by the class to be "properly" injected. (This is the school of thought which considers something like a Service Locator to be an anti-pattern.) There's merit to this, but taken to an extreme you find yourself where you are now. Just the right kind of complexity in some composite models, which themselves have composite models, results in aggregate roots which need tons of dependencies injected solely to satisfy dependencies of deeper models.
Personally I find that this creates coupling in situations like this. Which is what DI is intended to resolve, not to create.
On the other hand, you have the school of thought which allows for a Service Locator approach, where models can internally invoke some common domain service to resolve a dependency for it. There's merit to this, but taken to an extreme you find that your dependencies are less known and there's a potential for runtime errors if any given dependency can't be resolved. (Basically, you can get errors at a higher level because consuming objects never knew that consumed objects needed something which wasn't provided.)
Personally I've used a service locator approach a lot (mostly because it's a very handy pattern for introducing DI to a legacy domain as part of a larger refactoring exercise, which is a lot of what I do professionally) and have never run into such issues.
There's yin and yang either way. And I think each solution space has its own balance. If you're finding that direct injection is making the system difficult to maintain, it may be worth investigating service location. Conversely, it may also be worth investigating if the overall domain model itself is inherently coupled and this DI issue is simply a symptom of that coupling and not the cause of it.
Yes, the entire intent of Dependency Injection is that you compose big object graphs up-front. You compose object graphs from the Composition Root, which is a place in your application that has the Single Responsibility of composing object graphs. That's not any particular Controller, but a separate class that composes Controllers with their dependencies.
The Composition Root must have access to all types it needs to compose, unless you want to get into late-binding strategies (which I'll generally advise against, unless there's a specific need).
I am firmly of the opinion that Service Locators are worse than Dependency Injection. They can be a useful legacy technique, and a useful stepping stone on to something better, but if you are designing something new, then steer clear.
The main reason for this is that Service Locators lead to code that has implicit dependencies, and this makes the code less clear and breaks encapsulation. It can also lead to run time errors instead of compile time errors, and Interacting Tests.
Your example uses Constructor Injection, which is usually the most appropriate form of Dependency Injection:
public ViewModelService(ICategoryRepository categoryRepository, IPasswordRepository passwordRepository, IModelValidatorService modelValidator) { ... }
This has explicit dependencies, which is good. It means that you cannot create the object without passing in its dependencies, and if you try to you will get a compile time error rather than a run time one. It also is good for encapsulation, as just by looking at the interface of the class you know what dependencies it needs.
You could do this using service locators as below:
public ViewModelService()
{
var categoryRepository = CategoryRepositoryServiceLocator.Instance;
var passwordRepository = PasswordRepositoryServiceLocator.Instance;
var modelValidator FModelValidatorServiceLocator.Instance;
...
}
This has implicit dependencies, that you cannot tell just by looking at the interface, you must also look at the implementation (this breaks encapsulation). You can also forget to set up one of the Service Locators, which will lead to a run time exception.
In your example I thinky your ViewModelService is good. It references abstractions (ICategoryRepository etc) and doesn't care about how these abstractions are created. The code you use to create the ViewModelService is a bit ugly, and I would recommend using an Inversion of Control container (such as Castle Windsor, StructureMap etc) to help here.
In Castle Windsor, you could do something like the following:
container.Register(Classes.FromAssemblyNamed("Repositories").Pick().WithServiceAllInterfaces());
container.Register(Component.For<IAccountService>().ImplementedBy<AccountService>());
container.Register(Component.For<IApplicationDBContext>().ImplementedBy<IApplicationDBContext>());
container.Register(Component.For<IApplicationSettingsService>().ImplementedBy<IApplicationSettingsService>());
var viewModelService = _container.Resolve<ViewModelService>();
Make sure to read and understand the "Register, Resolve, Release" and "Composition Root" patterns before you start.
Good luck!

Best way of using IoC for production and Testing

When using IoC for dependency injection the most recommended use is constructor injection (as told by many articles), my question is :
Is it better to inject using the constructor parameters or passing the IoC container through the constructor to inject the classes needed, and what is more useful for unit testing ?
Although passing the container through the constructor is better than making the container accessible as a singleton for the complete application, it is still a form of Service Locator (anti-pattern), and is not recommended. This has clear disadvantages:
It makes your code much harder to follow.
It makes it much less obvious when the Single Responsibility Principle is violated (since the class hides which things it depends on).
It makes it much hard to test, since you need to pass a configured container and you need to look in the code to see what the test need.
When requesting instances from the container directly from within every class, you will disable many features that IOC containers give you, because you don't allow the container to build up the object graph. Depending on the framework of choice, certain lifestyles and features like context based injection will not be usable.
All your tests use a container instance, making your tests come complex, and all your test have a dependency on the DI framework, which makes it very expensive to switch to another framework when needed.
Just inject the dependencies into the constructor, never* the container itself.
*Exception to this rule is when such class is located inside the appliation's Composition Root. In that case it's not considered to be the Simple Locator pattern, because that class is simply an infrastructure component.
Using constructor/property injection is better. When you pass the IOC container to the constructor you are no longer doing dependency injection and inversion of control. You are doing the Service Locator pattern. This means that classes no longer get their dependencies injected by the consumer, but they try are trying to fetch them. You are also probably tying your code to some particular DI framework.

Dependency Inject (DI) "friendly" library

I'm pondering the design of a C# library, that will have several different high level functions. Of course, those high-level functions will be implemented using the SOLID class design principles as much as possible. As such, there will probably be classes intended for consumers to use directly on a regular basis, and "support classes" that are dependencies of those more common "end user" classes.
The question is, what is the best way to design the library so it is:
DI Agnostic - Although adding basic "support" for one or two of the common DI libraries (StructureMap, Ninject, etc) seems reasonable, I want consumers to be able to use the library with any DI framework.
Non-DI usable - If a consumer of the library is using no DI, the library should still be as easy to use as possible, reducing the amount of work a user has to do to create all these "unimportant" dependencies just to get to the "real" classes they want to use.
My current thinking is to provide a few "DI registration modules" for the common DI libraries (e.g a StructureMap registry, a Ninject module), and a set or Factory classes that are non-DI and contain the coupling to those few factories.
Thoughts?
This is actually simple to do once you understand that DI is about patterns and principles, not technology.
To design the API in a DI Container-agnostic way, follow these general principles:
Program to an interface, not an implementation
This principle is actually a quote (from memory though) from Design Patterns, but it should always be your real goal. DI is just a means to achieve that end.
Apply the Hollywood Principle
The Hollywood Principle in DI terms says: Don't call the DI Container, it'll call you.
Never directly ask for a dependency by calling a container from within your code. Ask for it implicitly by using Constructor Injection.
Use Constructor Injection
When you need a dependency, ask for it statically through the constructor:
public class Service : IService
{
private readonly ISomeDependency dep;
public Service(ISomeDependency dep)
{
if (dep == null)
{
throw new ArgumentNullException("dep");
}
this.dep = dep;
}
public ISomeDependency Dependency
{
get { return this.dep; }
}
}
Notice how the Service class guarantees its invariants. Once an instance is created, the dependency is guaranteed to be available because of the combination of the Guard Clause and the readonly keyword.
Use Abstract Factory if you need a short-lived object
Dependencies injected with Constructor Injection tend to be long-lived, but sometimes you need a short-lived object, or to construct the dependency based on a value known only at run-time.
See this for more information.
Compose only at the Last Responsible Moment
Keep objects decoupled until the very end. Normally, you can wait and wire everything up in the application's entry point. This is called the Composition Root.
More details here:
Where should I do Injection with Ninject 2+ (and how do I arrange my Modules?)
Design - Where should objects be registered when using Windsor
Simplify using a Facade
If you feel that the resulting API becomes too complex for novice users, you can always provide a few Facade classes that encapsulate common dependency combinations.
To provide a flexible Facade with a high degree of discoverability, you could consider providing Fluent Builders. Something like this:
public class MyFacade
{
private IMyDependency dep;
public MyFacade()
{
this.dep = new DefaultDependency();
}
public MyFacade WithDependency(IMyDependency dependency)
{
this.dep = dependency;
return this;
}
public Foo CreateFoo()
{
return new Foo(this.dep);
}
}
This would allow a user to create a default Foo by writing
var foo = new MyFacade().CreateFoo();
It would, however, be very discoverable that it's possible to supply a custom dependency, and you could write
var foo = new MyFacade().WithDependency(new CustomDependency()).CreateFoo();
If you imagine that the MyFacade class encapsulates a lot of different dependencies, I hope it's clear how it would provide proper defaults while still making extensibility discoverable.
FWIW, long after writing this answer, I expanded upon the concepts herein and wrote a longer blog post about DI-Friendly Libraries, and a companion post about DI-Friendly Frameworks.
The term "dependency injection" doesn't specifically have anything to do with an IoC container at all, even though you tend to see them mentioned together. It simply means that instead of writing your code like this:
public class Service
{
public Service()
{
}
public void DoSomething()
{
SqlConnection connection = new SqlConnection("some connection string");
WindowsIdentity identity = WindowsIdentity.GetCurrent();
// Do something with connection and identity variables
}
}
You write it like this:
public class Service
{
public Service(IDbConnection connection, IIdentity identity)
{
this.Connection = connection;
this.Identity = identity;
}
public void DoSomething()
{
// Do something with Connection and Identity properties
}
protected IDbConnection Connection { get; private set; }
protected IIdentity Identity { get; private set; }
}
That is, you do two things when you write your code:
Rely on interfaces instead of classes whenever you think that the implementation might need to be changed;
Instead of creating instances of these interfaces inside a class, pass them as constructor arguments (alternatively, they could be assigned to public properties; the former is constructor injection, the latter is property injection).
None of this presupposes the existence of any DI library, and it doesn't really make the code any more difficult to write without one.
If you're looking for an example of this, look no further than the .NET Framework itself:
List<T> implements IList<T>. If you design your class to use IList<T> (or IEnumerable<T>), you can take advantage of concepts like lazy-loading, as Linq to SQL, Linq to Entities, and NHibernate all do behind the scenes, usually through property injection. Some framework classes actually accept an IList<T> as a constructor argument, such as BindingList<T>, which is used for several data binding features.
Linq to SQL and EF are built entirely around the IDbConnection and related interfaces, which can be passed in via the public constructors. You don't need to use them, though; the default constructors work just fine with a connection string sitting in a configuration file somewhere.
If you ever work on WinForms components you deal with "services", like INameCreationService or IExtenderProviderService. You don't even really know what what the concrete classes are. .NET actually has its own IoC container, IContainer, which gets used for this, and the Component class has a GetService method which is the actual service locator. Of course, nothing prevents you from using any or all of these interfaces without the IContainer or that particular locator. The services themselves are only loosely-coupled with the container.
Contracts in WCF are built entirely around interfaces. The actual concrete service class is usually referenced by name in a configuration file, which is essentially DI. Many people don't realize this but it is entirely possible to swap out this configuration system with another IoC container. Perhaps more interestingly, the service behaviors are all instances of IServiceBehavior which can be added later. Again, you could easily wire this into an IoC container and have it pick the relevant behaviors, but the feature is completely usable without one.
And so on and so forth. You'll find DI all over the place in .NET, it's just that normally it's done so seamlessly that you don't even think of it as DI.
If you want to design your DI-enabled library for maximum usability then the best suggestion is probably to supply your own default IoC implementation using a lightweight container. IContainer is a great choice for this because it's a part of the .NET Framework itself.
EDIT 2015: time has passed, I realize now that this whole thing was a huge mistake. IoC containers are terrible and DI is a very poor way to deal with side effects. Effectively, all of the answers here (and the question itself) are to be avoided. Simply be aware of side effects, separate them from pure code, and everything else either falls into place or is irrelevant and unnecessary complexity.
Original answer follows:
I had to face this same decision while developing SolrNet. I started with the goal of being DI-friendly and container-agnostic, but as I added more and more internal components, the internal factories quickly became unmanageable and the resulting library was inflexible.
I ended up writing my own very simple embedded IoC container while also providing a Windsor facility and a Ninject module. Integrating the library with other containers is just a matter of properly wiring the components, so I could easily integrate it with Autofac, Unity, StructureMap, whatever.
The downside of this is that I lost the ability to just new up the service. I also took a dependency on CommonServiceLocator which I could have avoided (I might refactor it out in the future) to make the embedded container easier to implement.
More details in this blog post.
MassTransit seems to rely on something similar. It has an IObjectBuilder interface which is really CommonServiceLocator's IServiceLocator with a couple more methods, then it implements this for each container, i.e. NinjectObjectBuilder and a regular module/facility, i.e. MassTransitModule. Then it relies on IObjectBuilder to instantiate what it needs. This is a valid approach of course, but personally I don't like it very much since it's actually passing around the container too much, using it as a service locator.
MonoRail implements its own container as well, which implements good old IServiceProvider. This container is used throughout this framework through an interface that exposes well-known services. To get the concrete container, it has a built-in service provider locator. The Windsor facility points this service provider locator to Windsor, making it the selected service provider.
Bottom line: there is no perfect solution. As with any design decision, this issue demands a balance between flexibility, maintainability and convenience.
What I would do is design my library in a DI container agnostic way to limit the dependency on the container as much as possible. This allows to swap out on DI container for another if need be.
Then expose the layer above the DI logic to the users of the library so that they can use whatever framework you chose through your interface. This way they can still use DI functionality that you exposed and they are free to use any other framework for their own purposes.
Allowing the users of the library to plug their own DI framework seems a bit wrong to me as it dramatically increases amount of maintenance. This also then becomes more of a plugin environment than straight DI.

StructureMap DI on Model Assembly

I’m new to Dependency Injection and had a question/need guidance.
I had an application that used the repository pattern for data access. I used StructureMap to get the correct repository and all worked well.
I have since broken out my model (including the repository logic) into its own assembly and added a service layer. In the interest of DI the service layer class takes an IRepository in its constructor. This seems wrong to me as now all consumers of my model need to know about the repository (at least configure their DI to know which one to use). I feel like that is getting into the guts of the model.
What sounds wrong with this?
An application written to use dependency injection typically configures a single container instance where all the interface/implementation type mappings have been registered at an initialization stage of the application. This would include the registration of the repositories, services, and any consumers of the service within the application.
By resolving the consumers of the service through the container, consumers need only indicate their dependency upon the service, not any dependencies the service might need. Therefore, the consumers of the service will not be coupled to its dependencies (e.g. your repository). This is the benefit of doing dependency injection through a container as opposed to doing manual dependency injection.
If you are designing services to be consumed by other applications in the form of a reusable library then your options will vary depending on the level of flexibility you wish to offer.
If you presume all clients of your library will be using dependency injection, then you will need to provide an appropriate amount of documentation about what types need to be registered within their container.
If you presume all clients will be using a specific container (e.g. StructureMap), then you can ease the registration requirements by providing registries which encapsulate all the specific registration needs for the client.
If you wish to allow your library to be used by clients not using their own dependency injection container then you can provide a static factory which returns the service. Depending on the level of complexity, such a scenario may not require use of a container (for example, if your service is comprised by just a few objects in all). If your library is comprised of a substantial amount of components which need to be composed then you might have factories which resolve the services through their own shared internal infrastructure initialization needs.
I understand your dilemma there Dan, I too spent lots of time wrestling over that in my mind. I believe the way I decided to go forward with was one of best ways to encapsulate all of the concerns and still have easily maintainable loosely coupled objects.
I wrote this blog post specifically about NHiberante but if you look at the repository pattern in implement you can easily change the NH specific code to use your backingstore.
Creating a common generic and extensible NHiberate Repository

Categories