Is the IServiceProvider basically just a generic interface for any IOC container, or is it used for a specific framework? I'm rolling my own light weight IOC container and I am wanting to know if I should implement it. Are there any other interfaces that I should implement? I'm not really interested in either MEF or Unity. I've used both extensively and they don't really work for my current project.
IServiceProvider is an imported (or perhaps held-over) COM interface that is intended to be used for private features in the context of the object whom you interrogate for a Service. The term 'Service' is applied rather loosely here, it originally meant any COM object that could be returned based upon what GUID is given.
IServiceProvider # MSDN (.NET reference)
IServiceProviderImpl Class # MSDN (C++ ATL reference)
In .NET, you don't need to implement it unless you have a client that specifically supports it, and in many cases you won't need to add yet another level of indirection that is implied by using IServiceProvider. Also, you can devise your own scheme to share common objects or implement other use patterns based upon IoC / Dependency Injection that are more flexible or more rigid as dictated by your needs.
One good historical context for IServiceProvider is the IE Browser Plugin Spec. Here, it is used to allow plugin components to use Browser Host features in-context. In a COM context, this interface is useful because it hides the details of instantiation and also can be used as part of a object construction and utilization strategy to avoid reference loops.
WebBrowser Customization (Part 2) # MSDN
I think it is a pretty general use interface, so you can use it with anything. It almost should not even be in the Framework Class Library. For one specific use, Alex D. James of the WCF Data Services team has a blog about it.
http://blogs.msdn.com/b/alexj/archive/2010/01/07/creating-a-data-service-provider-part-2-iserviceprovider-datasources.aspx
I do not think it has anything to do with IoC containers. I have used Unity and Autofac quite a bit and have never seen it used with either. As for rolling your own, I would suggest you define your own container interface in the more standard generic way:
public interface IContainer
{
T Resolve<T>();
}
That is pretty standard with some variation, but you could also just use IServiceProvider if that fits your needs.
And on that note, unless this is just an academic exercise, you might want to read "Dependency Injection". Mark Seemann covers every container out there and quite a bit of theory and practice. That is, I highly recommend it.
https://www.amazon.com/Dependency-Injection-NET-Mark-Seemann/
ASP.NET 5 uses IServiceProvider in "self-hosted" mode, that is, when hosting an ASP.NET application and the runtime in a console application or service.
(An object of type Microsoft.Framework.Runtime.Common.DependencyInjection.ServiceProvider -- which implements IServiceProvider -- is passed to your console app constructor.)
Thus, if you wanted to use a different IoC container in ASP.NET 5, you might want to implement this interface. Or wrap the other IoC container in a class which implements this interface.
The new (as of .NET 4) Runtime Caching API also uses it: http://msdn.microsoft.com/en-us/library/system.runtime.caching.objectcache.host.aspx.
And also Visual Studio designer.
Related
I might be overthinking this. I hope so.
In our .Net 4.5, C# 5 Windows service, we're using Castle Windsor 3.2 with the CollectionResolver installed. We have an interface IEncryptionService that does what you'd expect, and two classes implement that interface. The service needs to integrate and bridge two other systems, by decrypting data from one and re-encrypting it for the other.
Both implementations have names according to their target system.
Component.For<IEncryptionService>()
.ImplementedBy<System1EncryptionService>()
.Named("system1-encryption")
.LifestyleTransient(),
Component.For<IEncryptionService>()
.ImplementedBy<System2EncryptionService>()
.LifestyleTransient()
.Named("system2-encryption"));
The Windows service class uses constructor injection to receive an array of type IEncryptionService[]. Both of the encryption classes are being injected.
Therein lies the problem: I need to use one implementation for one system, and the other for the other. The way I've implemented it thus far, they're indistinguishable from each other.
What is the solution here? A typed factory seems like an anti-pattern covering up an architectural flaw. But its the only thing I've come up with. I've named my components; can I take advantage of that in other components? Or should I just forget injection and instantiate them directly?
I figure this sort of situation happens often enough that there's probably a standard way of handling it.
When you register your component which depends on the two, you specify the names of the arguments corresponding to the injected classes in the Compnent.For line:
Component.For<IServiceUsingTheEncryption>()
.ImplementedBy<ServiceUsingTheEncryption>()
//.LifestyleOfYourChoosing
.ServiceOverrides(
ServiceOverride.ForKey("encryptionService1").Eq("system1-encryption"),
ServiceOverride.ForKey("encryptionService2").Eq("system2-encryption"));
And in the ctor of your ServiceUsingTheEncryption, you would specify the arguments as such:
public ServiceUsingTheEncryption(IEncryptionService encryptionService1, IEncryptionService encryptionService2) {
// ...
}
I need to fetch data from an external API, only accessible via VPN.
The development/test machine will not always be able to connect to the VPN.
The desired behaviour is to use two different implementations (one that calls the actual external API and one that acts as the real thing but returns dummy data). Which implementation to use will be configured via a flag in web.config
I've tried the IoC containers StructureMap and Unity and they both did the job but they only seem to be applicable for MVC, I'm looking for a generic solution that also works for web forms. And also, isn't it a bit overkill to use them for this isolated design problem!?
Is there a design pattern or best practice approach for this particular scenario?
IoC / dependency injection sounds like the correct approach, but you don't necessarily need a container for a simple scenario. The key is to have classes that depend on the API reference an interface IAPI, and pass it the actual implementation RealAPI or FakeAPI.
public class SomeClass
{
private readonly IAPI _api;
public SomeClass(IAPI api)
{
_api = api;
}
}
Now you should be able to switch out the implementation easily by passing a different object to MyClass. In theory, when you're using an IoC approach, you should only need to bind the interface to the implementation once, at the top level of the application.
isn't it a bit overkill to use them for this isolated design problem!?
They probably are. Those IoC containers only help you when you wrote loosly coupled code. If you didn't design your classes according to the SOLID principles for instance, those frameworks will probably only be in the way. On the other hand, which developer doesn't want to write loosly coupled code? In other words, IoC container solves a problem you might not have but it's a nice problem to have.
StructureMap and Unity [...] only seem to be applicable for MVC
Those ioc frameworks can be used in any type of application (as long as it is written in loosly coupled way). Some types of applications need a bit more work to plug a framework in, but it's always possible. StructureMap and Unity might only have integration packages for MVC, it's quite easy to use them in ASP.NET Web Forms as well.
Is there a design pattern or best practice approach for this
particular scenario?
What you're looking for is the Proxy pattern and perhaps the circuit breaker pattern.
I'm building a CMS and it has many extension points (Data/ContentTypes, Plugins, Macros, Themes) and some of those extensions need to register services. So far extensions only depend on 'MyProject.Core' library and it would be nice if they wouldn't be dependant on any specific IoC framework. Now I'm thinking if I should build another layer to hide IoC specific registrations. The problem is that I need some advanced functionality.
E.g. NHibernate implementation of 'Data/ContentType' services (Castle Windsor style)
container.Register(Component.For<IPageRepository>().ImplementedBy<NHPageRepository>());
container.Register(Component.For<ISessionFactory>().Instance(NHibernateHelper.CreateSessionFactory()));
container.Register(Component.For<ISession>().UsingFactoryMethod(c => c.Resolve<ISessionFactory>().OpenSession()).LifeStyle.PerWebRequest);
Third line is the "hard one". I could make an interface like
interface IMyContainer
{
Register<TService>(Func<IMyContainer,TService> factoryMethod)
Register<TService>(Func<IMyContainer,TService> factoryMethod, LifeStyle lifeStyle)
// ...
}
but "translating" this registration (my IoC abstraction)
public class NHInstaller : IInstaller
{
public void Install(IMyContainer container)
{
container.Register<ISession>(c => c.Resolve<ISessionFactory>().OpenSession(), LifeStyle.PerRequest);
}
}
to this (Windsor)
container.Register(Component.For<ISession>().UsingFactoryMethod(c => c.Resolve<ISessionFactory>().OpenSession()).LifeStyle.PerWebRequest);
could be quite hard.
So, should I try to make that abstraction? Any helpful resources?
Or should I just pick a IoC container and stick with it?
I could also make source code of an existing tool (Castle Windsor or Ninject) a part of my library, but I don't really understand those licenses. Can I do that? Can I change namespaces and class names to fit the structure of my app? I'm going to release the source code and I don't really care what the license is going to be.
It depends on what you mean by "hide." Best practice is that only one place in your application (the Composition Root) knows about the IoC container. Stick to the Hollywood Principle - avoid having multiple classes that know about the IoC container. In other words don't pass the container around; if a non-root class needs to create other objects then inject a factory into it.
If you're writing a framework and want to allow consumers to plug in their IoC container framework of choice, you could use the Common Service Locator library. That is likely overkill for most projects. (See Mark Seemann's excellent link for the reason I changed the wording).
Short answer - no, the abstraction is useless, you'd be wasting your employer's money. Use Installers to partition the registration instead.
In which scenario should we use which? How to decide on which one to choose? And under which circumstances would we choose to use both together?
I have previously worked with Unity Container (unity-container).
Tricky question - since the two do indeed overlap to a certain degree.
I would say this:
use any useful IoC if you're primarily concerned about dependency injection for the sake of decoupling your components, e.g. for the ability to be able to inject a mock instead (for testing)
use MEF especially if you're more into being extensible, e.g. be able to "load all assemblies from that directory that export a certain interface", and if you need to be extensible and open for third parties (like Visual Studio: offer a public API so others can write an extension for your app). This is where MEF really shines
For MEF and Unity, there's also the MEF and Unity Integration Layer to combine the strengths of both tools together.
I would also recommend you check out Ayende's excellent blog post on what differentiates MEF from an IoC.
MEF shines when you have 3rd parties writing plug-ins, that implement interfaces and you wish to be able to version your interface without breaking the 3rd party plug in you can’t recompile. In exchange MEF is more complex than a raw IoC.
So I would say IoC if everything is compiled as part of the same build system, and MEF if you need to cope with add-ins you can’t recompile yourself.
Glen Block (former Product Manager of MEF) has covered this pretty well on his blog:
Should I use MEF for my general IoC needs?
Should I use MEF with an IoC container? - Part 1
I heard a great explanation of this (apologies to the author, I've forgotten who it was): At a very high level, IoC is good when you want one thing for a given interface, MEF is good for when you want all things from a given interface.
For instance in IoC you want to return a specific single concrete class for an interface:
For<ICarFactory>().Use<CarFactory>();
Whenever you want to use a ICanFactory you will get a CarFactory.
MEF is good for saying give me all the car factories:
CheapCarFactory : ICarFactory
FamilyCarFactory : ICarFactory
LuxuryCarFactory : ICarFactory
Etc.
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