Dynamic selection of interface implementation using IoC - c#

I have a situation where the implementation of an interface is determined at runtime. For example, I check a string and then determine which subclass to use, without IoC it looks like the following:
if (fruitStr == "Apple")
{
new AppleImpl().SomeMethod();
}
else
{
new BananaImpl().SomeMethod();
}
Both classes AppleImpl and BananaImpl are implementation of the same interface, say IFruit.
How can this be done using IoC/Dependency Injection, especially in Castle Windsor?

This is the single most-asked question about Dependency Injection, and gets asked over and over again on StackOverflow.
In short, it is best to use patterns to solve runtime creation rather than trying to use the container for more than composing object graphs, which is all it is designed for.
There are several patterns that can be used for this, but among the best options are to use Abstract Factory, Strategy, or a combination of the two. The exact solution depends on how the instance will be used - use a factory if you will be needing several short-lived instances and want to discard them after use, or use a strategy if you need to use the instances over and over again in a loop without having to recreate them each time. The combination is a tradeoff between high performance and low memory consumption.

Related

DI in class library [duplicate]

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.

C# Dependency injection side effect (two step initialization anti-pattern)? [duplicate]

This question already has answers here:
Is there a pattern for initializing objects created via a DI container
(5 answers)
Closed 7 years ago.
I'm working on a project in which my constructors contain - only - behavioral dependencies. i.e. I never pass values / state.
Example:
class ProductProcessor : IProductProcessor
{
public double SomeMethod(){ ... }
}
class PackageProcessor
{
private readonly IProductProcessor _productProcessor;
private double _taxRate;
public PackageProcessor(IProductProcessor productProcessor)
{
_productProcessor = productProcessor;
}
public Initialize(double taxRate)
{
_taxRate = taxRate;
return this;
}
public double ProcessPackage()
{
return _taxRate * _productProcessor.SomeMethod();
}
}
In order to pass state, it was decided to include a second step (a call to Initialize).
I know we can configure this as a named parameter in the IoC Container config class, however, we did not like the idea of creating "new namedParameter(paramvalue)'s" in the configuration file as it makes it unnecessarily unreadable and creates a future maintenance pain spot.
I've seen this pattern in more than one place.
Question: I read some consider this two step initialization an anti-pattern. If that is the consensus, wouldn't this imply a limitation / weakness of sorts in the approach of dependency injection via a IoC container?
Edit:
After looking into Mark Seeman's suggestion:
and the answers to this one, I have a few comments:
Initialize/Apply : Agree on it being an anti pattern / smell.
Yacoub Massad: I agree IoC containers are a problem when it comes to primitive dependencies. Manual (poor man's) DI, as described here sounds great for smaller or architecturally stable systems but I think it could become very hard to maintain a number of manually configured composition roots.
Options:
1)Factories as dependencies (when run time resolution is required)
2) Separate stateful object from pure services as described here.
(1): This is what I had been doing but I realized that there is a potential to incur into a another anti-pattern: the service locator.
(2): My preference for my particular case is this one about this one as I can cleanly separate both types. Pure services are a no brainer - IoC Container, whereas stateful object resolution will depend on whether they have primitive dependencies or not.
Every time I've 'had' to use dependency injection, it has been used in a dogmatic way, generally under the orders of a supervisor bent on applying DI with IoC container at any cost.
I read some consider this two step initialization an anti-pattern
The Initialize method leads to Temporal Coupling. Calling it an anti-pattern might be too strict, but it sure is a Design Smell.
How to provide this value to the component depends on what type of value it is. There are two flavors: configuration values and runtime values:
Configuration Values: If it is a constant/configuration value that won't change during the lifetime of the component, the value should be injected into the constructor directly.
Runtime values: In case the value changes during runtime (such as request specific values), the value should not be provided during initialization (neither through the constructor nor using some Initialize method). Initializing components with runtime data actually IS an anti-pattern.
I partly agree with #YacoubMassad about the configuration of primitive dependencies using DI containers. The APIs provided by containers do not enable setting those values in a maintainable way when using auto-wiring. I think this is mainly caused by limitations in C# and .NET. I struggled a long time with such API while designing and developing Simple Injector, but decided to leave out such API completely, because I didn't find a way to define an API that was both intuitive and lead to code that was easy maintainable for the user. Because of this I usually advise developers to extract the primive types into Parameter Objects and instead register and inject the Parameter Object into the consuming type. In other words, a TaxRate property can be wrapped in a ProductServiceSettings class and this Parameter Object can be injected into ProductProcessor.
But as I said, I only partly agree with Yacoub. Although it is more practical to compose some of your objects by hand (a.k.a. Pure DI), he implies that this means you should abandon DI containers completely. IMO that is too strongly put. In most of the applications I write, I batch-register about 98% of my types using the container, and I hand-wire the other two 2%, because auto-wiring them is too complex. This gives in the context of my applications the best overall result. Of course, you're mileage may vary. Not every application really benefits from using a DI container, and I don't use a container myself in all the application I write. But what I always do however, is apply the Dependency Injection pattern and the SOLID principles.
The taxRate in your example is a Primitive Dependency. And primitive dependencies should be injected normally in the constructor like the other dependencies. Here is how the constructor would look like:
public PackageProcessor(IProductProcessor productProcessor, double taxRate)
{
_productProcessor = productProcessor;
_taxRate = taxRate;
}
The fact that DI containers do not nicely/easily support primitive dependency is a problem/weakness of DI containers in my opinion.
In my opinion, it is better to use Pure DI for object composition instead of a DI container. One reason is that it supports easier injection of primitive dependencies. See this article also for another reason.
Using the Initialize method has some problems. It makes the construction of an object more complex by requiring the invocation of the Initialize method. Also, a programmer might forget to call the Initialize method, which leaves your object in an invalid state. This also means that the taxRate in this example is a hidden dependency. Programmers wouldn't know that your class depends on such primitive dependency by simply looking into the constructor.
Another problem with the Initialize method is that it might be called twice with different values. Constructors on the other hand, ensure that dependencies do not change. You would need to create a special boolean variable (e.g. isInitialized) to detect if the Initialize method has been called already. This just complicates things.

Does Dependency Injection (DI) rely on Interfaces?

This may seem obvious to most people, but I'm just trying to confirm that Dependency Injection (DI) relies on the use of Interfaces.
More specifically, in the case of a class which has a certain Interface as a parameter in its constructor or a certain Interface defined as a property (aka. Setter), the DI framework can hand over an instance of a concrete class to satisfy the needs of that Interface in that class. (Apologies if this description is not clear. I'm having trouble describing this properly because the terminology/concepts are still somewhat new to me.)
The reason I ask is that I currently have a class that has a dependency of sorts. Not so much an object dependency, but a URL. The class looks like this [C#]:
using System.Web.Services.Protocols;
public partial class SomeLibraryService : SoapHttpClientProtocol
{
public SomeLibraryService()
{
this.Url = "http://MyDomainName.com:8080/library-service/jse";
}
}
The SoapHttpClientProtocol class has a Public property called Url (which is a plain old "string") and the constructor here initializes it to a hard-coded value.
Could I possibly use a DI framework to inject a different value at construction? I'm thinking not since this.Url isn't any sort of Interface; it's a String.
[Incidentally, the code above was "auto-generated by wsdl", according to the comments in the code I'm working with. So I don't particularly want to change this code, although I don't see myself re-generating it either. So maybe changing this code is fine.]
I could see myself making an alternate constructor that takes a string as a parameter and initializes this.Url that way, but I'm not sure that's the correct approach regarding keeping loosely coupled separation of concerns. (SoC)
Any advice for this situation?
DI really just means a class wont construct it's external dependencies and will not manage the lifetime of those dependencies. Dependencies can be injected either via constructor, or via method parameter. Interfaces or abstract types are common to clarify the contract the consumer expects from its dependency, however simple types can be injected as well in some cases.
For example, a class in a library might call HttpContext.Current internally, which makes arbitrary assumptions about the application the code will be hosted in. An DI version of the library method would expect a HttpContext instance to be injected via parameter, etc.
It's not required to use interfaces -- you could use concrete types or abstract base classes. But many of the advantages of DI (such as being able to change an implementation of a dependancy) come when using interfaces.
Castle Windsor (the DI framework I know best), allows you to map objects in the IoC container to Interfaces, or to just names, which would work in your case.
Dependency Injection is a way of organizing your code. Maybe some of your confusion comes from the fact that there is not one official way to do it. It can be achieved using "regular" c# code , or by using a framework like Castle Windsor. Sometimes (often?) this involves using interfaces. No matter how it is achieved, the big picture goal of DI is usually to make your code easier to test and easier to modify later on.
If you were to inject the URL in your example via a constructor, that could be considered "manual" DI. The Wikipedia article on DI has more examples of manual vs framework DI.
I would like to answer with a focus on using interfaces in .NET applications. Polymorphism in .NET can be achieved through virtual or abstract methods, or interfaces.
In all cases, there is a method signature with no implementation at all or an implementation that can be overridden.
The 'contract' of a function (or even a property) is defined but how the method is implemented, the logical guts of the method can be different at runtime, determined by which subclass is instantiated and passed-in to the method or constructor, or set on a property (the act of 'injection').
The official .NET type design guidelines advocate using abstract base classes over interfaces since they have better options for evolving them after shipping, can include convenience overloads and are better able to self-document and communicate correct usage to implementers.
However, care must be taken not to add any logic. The temptation to do so has burned people in the past so many people use interfaces - many other people use interfaces simply because that's what the programmers sitting around them do.
It's also interesting to point out that while DI itself is rarely over-used, using a framework to perform the injection is quite often over-used to the detriment of increased complexity, a chain-reaction can take place where more and more types are needed in the container even though they are never 'switched'.
IoC frameworks should be used sparingly, usually only when you need to swap out objects at runtime, according to the environment or configuration. This usually means switching major component "seams" in the application such as the repository objects used to abstract your data layer.
For me, the real power of an IoC framework is to switch implementation in places where you have no control over creation. For example, in ASP.NET MVC, the creation of the controller class is performed by the ASP.NET framework, so injecting anything is impossible. The ASP.NET framework has some hooks that IoC frameworks can use to 'get in-between' the creation process and perform their magic.
Luke

Strategy Design pattern with IOC containers - Ninject specifically

I have a class which is going to need to use the strategy design pattern. At run time I am required to switch different algorithms in and out to see the effects on the performance of the application.
The class in question currently takes four parameters in the constructor, each representing an algorithm.
How using Ninject (or a generalised approach) could I still use IOC but use the strategy pattern?
The current limitation is that my kernel (container) is aware of each algorithm interface, but that can only be bound to one concrete class. The only way around this I can see at the moment is pass in all eight algorithms at construction, but use different interfaces, but this seems totally uncessary. I wouldn't do this if I was not using an IOC container, so there must be some way around this.
Code example:
class MyModule : NinjectModule
{
public override void Load()
{
Bind<Person>().ToSelf();
Bind<IAlgorithm>().To<TestAlgorithm>();
Bind<IAlgorithm>().To<ProductionAlgorithm>();
}
}
Person needs to make use of both algorithms so I can switch at run time. But only TestAlgorithm is bound, as it's the first one in the container.
Let's take a step back and examine a slightly bigger picture. Since you want to be able to switch Strategy at run-time, there must be some kind of signalling mechanism that tells Person to switch the Strategy. If you application is UI-driven, perhaps there a button or drop-down list where the user can select which Strategy to use, but even if this is not the case, some outside caller must map a piece of run-time data to an instance of the Strategy.
The standard DI solution when you need to map a run-time instance to a dependency is to use an Abstract Factory.
Instead of registering the individual Strategies with the container, you register the factory.
It is entirely possible to write a complete API so that it's DI-friendly, but still DI Container-agnostic.
If you need to vary the IAlgorithm implementation at run-time, you can change Person to require an algorithm factory that provides different concrete algorithms based on run-time conditions.
Some dependency injection containers let you bind to anonymous creational delegates - if Ninject supports that, you could put the decision logic in one of those.

When to use activator and when to use factory method?

I have learnt the factory method design pattern, and at the same time, I have come across the Activator object and how to use it, from reading a tutorial (I have come across this object in intellisense a lot thougha).
Activator allows late binding, which can be extremely useful. But this is because we don't know what class we want to instantiate. Likewise, the factory method deals with the same problem in software engineering.
At a simple level, a bunch of ifs or a case statement and then instantiating an object based on the if condition is an implementation of the factory method, right?
On on a related topic, I have read that polymorphism can reduce coupling between objects by eliminating case statements. Is there an example of this?
Thanks
If you know at compile time all of the potential classes you would want to instantiate, use the Factory pattern, it will be faster and lets the compiler check your type safety.
On the other hand, if you don't know all of the classes that might need to be instantiated (for example, if you are trying to provide a plugin architecture), your only option is to use Activator.
The simple rule of thumb here is this: Choose a factory over using Activator (or any other type of runtime binding) as long as the scenario allows it.

Categories