IOC in Winforms plugin architecture - c#

I am working with an architecture that has a main program. When this starts it looks in the executing path via reflection for DLL's that have inherited off a base class. These are the plugins.
When a new requirement for a new project arises typically a new plugin is created. This plugin has the main plugin class and then possibly a number of other classes and windows forms.
The main plugin class has initialize methods but as its a class library there is no program.cs so to speak to wire up dependencies.
Is there a way via an app.config to wire up dependencies or do you think I should avoid using an IOC Container and just have a factory method in the plugin class that wires up the dependencies some how?
The issue is I may not have the ability to change the main application's code to setup the IOC container

All major IoC containers have the ability to wire up dependencies with app.config or via an assembly discovery mechanism (like you describe). Typically the main application sets up the container, and then defers to the container to find the plugins (which may be configured via configuration or by assembly probing like you describe above).
For SpringFramework.net, as an example of app.config: http://www.springframework.net/doc-latest/reference/html/objects.html#d4e437
For Castle Windsor, an example of assembly probing: http://stw.castleproject.org/Windsor.Installers.ashx

Whilst I think your question is a bit vague, based on what I gather from your question I would have to say IoC would most likely be the best way to go! You can use your IoC container to wire up the factories if you like, or you can use it to wire up the PlugIn dependencies, Personally, I like to use StructureMap. A very versatile and easy to use IoC container.
You could use the app.config to list the dependancy names and then feed the IoC the names to create dependencies. Use something like Activator to then create instances. Personally, I would use both IoC and factories. I would use the app.config to specify the dependency names and then use a Factory to dish out the instances of the plugIn classes. And finally I would then use the IoC container to specify the implementation of the factory(ies).
Hope that is of some use!

Related

Interfaces, business logic and global.asax with Autofac

I'm trying to figure out how separation should work with ASP.NET and dependency injection.
I have four projects:
ASP.NET Client
BusinessLogic class lib (BL)
Integration class lib, calling Service references
Shared (Interfaces, Models)
In Integration I have a repository, which calls other services. The repository "MyRepository" implements an interface "IMyRepository", which is placed in Shared, and returns objects which are also placed in Shared.
Strictly speaking, I would not like a reference/dependency from the Client to the Integration-project, but all communication should happen through BL.
In the Client's Global.asax, I register my types with Autofac
var builder = new ContainerBuilder();
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MyRepository>().As<IMyRepository>().InstancePerHttpRequest();
However this requires the Client-project to reference the Integration-project for the implementation of MyRepository. Should it be this way?
How can I not have a reference from Client to Integration and keep the separation clean?
My real world project is on a much larger scale than this, so I'm trying to untangle the dependencies.
Thanks for your time!
My normal approach is:
Define a way to discover types in each individual assembly. Easiest approach (if you do not mind referencing Autofac in each) is to put an Autofac Module in each assembly. If you do not like that, you can define your own discovery abstraction (for example, MEF-like attributes).
Discover all assemblies. Easiest approach is to scan the bin folder, but you can use some custom configuration. I haven't checked latest versions of Autofac add anything in terms of module discovery, but previously I did it manually.
Use previously defined type discovery approach to register all relevant types from each discovered assembly.

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.

Is an IoC container an overkill for a very simple framework

I am creating a library that integrates our product with another 3rd party product.
The design being used involves an interface that abstracts the core operations i'd like to integrate to our product, such that when a new 3rd party API is released, we would transparently switch to using it instead of the old one without modifying existing code.
To this end, the actual code that will return a concrete instance of the object interacting with 3rd party API needs to make a decision on to "which implementation to select".
For the simple needs, i assume an entry in the configuration file would suffice to say the fully qualified implementing class name.
Should i use an IoC container in this case, or should i use a Factory Method pattern and code it myself? (use reflection to instantiate the object, etc).
What are the pros and cons for this? Am i missing anything?
Quoting Mark Seemann:
Applications should depend on containers. Frameworks should not.
An IoC container sounds like overkill for your problem. If you have only one dependency to inject, doing it via the config file should be just fine.
Any IoC container is never overkill. You WILL eventually expand on this app if it's successful, or at the least used regularly and you will get requests to add more.
I'm a Castle user, and it's darn easy to add Castle with NuGet then just create a new WindsorContainer() in the startup and register your interfaces and class.
It's like asking if TDD is overkill to make a simple app. You should always (if you can) TDD the app, and use interfaces over concrete in your classes. IoC is too easy to setup now that you're only adding a few lines of code, so why not? it will be much harder later on if you didn't originally use an IoC container and you have intefaces and newed up classes all over your project to organize them all back into an IoC container.

C# method that is executed after assembly is loaded

I write some C# class libary and I want to use Ninject to provide dependency injection for my classes. Is it possible for class libary to declare some code (method) that would be executed each fime the class libary is loaded. I need this to define bindings for Ninject.
It sounds like you are looking for the equivalent of C++'s DllMain. There is no way to do this in C#.
Can you give us some more information about your scenario and why you need code to execute in a DllMain style function?
Defining a static constructor on a type does not solve this problem. A static type constructor is only guaranteed to run before the type itself is used in any way. You can define a static constructor, use other code within the Dll that does not access the type and it's constructor will never run.
I have used Ninject quite a bit over the last 9 months. Sounds like what you need to do is "load" your modules that exist in your libray into the Ninject kernel in order to register the bindings.
I am not sure if you're using Ninject 1.x or the 2.0 beta. The two versions perform things slightly differently, though conceptually, they are the same. I'll stick with version 1.x for this discussion. The other piece of information I don't know is if your main program is instantiating the Ninject kernel and your library is simply adding bindings to that kernel, or if your library itself contains the kernel and bindings. I am assuming that you need to add bindings in your library to an existing Ninject kernel in the main assembly. Finally, I'll make the assumption that you are dynamically loading this library and that it's not statically linked to the main program.
The first thing to do is define a ninject module in your library in which you register all your bindings -- you may have already done this, but it's worth mentioning. For example:
public class MyLibraryModule : StandardModule {
public override void Load() {
Bind<IMyService>()
.To<ServiceImpl>();
// ... more bindings ...
}
}
Now that your bindings are contained within a Ninject module, you can easily register them when loading your assembly. The idea is that once you load your assembly, you can scan it for all types that are derived from StandardModule. Once you have these types, you can load them into the kernel.
// Somewhere, you define the kernel...
var kernel = new StandardKernel();
// ... then elsewhere, load your library and load the modules in it ...
var myLib = Assembly.Load("MyLibrary");
var stdModuleTypes = myLib
.GetExportedTypes()
.Where(t => typeof(StandardModule).IsAssignableFrom(t));
foreach (Type type in stdModuleTypes) {
kernel.Load((StandardModule)Activator.CreateInstance(type));
}
One thing to note, you can generalize the above code further to load multiple libraries and register multiple types. Also, as I mentioned above, Ninject 2 has this sort of capability built-in -- it actually has the ability to scan directories, load assemblies and register modules. Very cool.
If your scenario is slightly different than what I've outlined, similar principles can likely be adapted.
Have you tried the AppDomain.AssemblyLoad event? It fires after an assembly has been loaded.
AppDomain.CurrentDomain.AssemblyLoad += (s, e) =>
{
Assembly justLoaded = e.LoadedAssembly;
// ... etc.
};
Can you control the client code? If yes, instead of trying to do magic when loading assembly, I would go for implementing a single class like Registry which does the bindings, implementing an interface IRegistry. Then during loading you can look for the implementation of IRegistry in your assembly and fire necessary methods.
You can also have attributes on your classes:
[Component(Implements=typeof(IMyDependency)]
look for these attributes and load them to the container on the client side.
Or you can take a look at MEF which is a library for these kind of situations.
As far as I know the answer is no
.As I understand you want to configure your IoC container in your class library and If that's the case it's not a good idea to do that.If you define your bindings in your class library then what's the use of dependency injection? we use dependency injection so that we can inject dependencies at runtime then we can inject different objects in different scenarios.Although the best place to configure an IoC container is the start up of your application (since an IoC container is like a backbone for an application :) ) but it should be placed at a bootstrap that is responsible to start the application.In simple applications it can be the Main method.

When would you use the Common Service Locator?

I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.
Do people recommend never using it? Always using it? or sometimes using it?
If sometimes, then in what situations would you use it and what situations would you not use it.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.
The Common Service Locator lets you cope with the above without forcing a given IoC on your users.
Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
I noticed that one of the arguments against using the CSL is a false one, because developers think this library is only capable of doing the Service Locator pattern. This however isn't the case, because it is easy to use it with the Dependency Injection pattern as well.
However, the CSL library was specially designed for framework designers who need to allows users to register dependencies. Because the library will be calling the CSL directly, from the framework's perspective we're talking about the SL pattern, hence its name.
As a framework designer however, taking a dependency on the CSL shouldn't be taking lightly. For usability of your framework it is normally much better to have your own DI mechanism. A very common mechanism is to set up dependencies in the configuration file. This pattern is used throughout the whole .NET framework. Almost every dependency can be replaced for another. The .NET provider pattern is built on top of this.
When you, as a framework designer, take a dependency on the CSL, it will be harder for users to use your application. Users will have to configure an IoC container and hook it up to the CSL. However, it is not possible for the framework to validate the configuration as can be done while using the .NET configuration system, which as all kind of validation support in it.
I've done some reading on the service locator concept lately. It is a way of helping to reduce coupling, but requires code coupling to the locator - not the container backing the locator, but the locator itself. It is a tradeoff, but can be beneficial in the right situation.
One situation where it can be helpful is when you have code that does not make use of DI, such as legacy code - I am in this boat now. Pulling in required objects via SL, rather than directly creating them, allows the addition of some abstraction. I see it as an intermediate step between SL and DI/IoC.
If you have library code that is in need of services and this code could be hosted in the context of a larger framework/runtime then the framework / runtime would need to provide a mechanism where you can run some custom code on startup wherein you can initialize your container and register dependencies.
A good example of where CSL can be problematic is when using it in the context of MSCRM. You can have custom business logic executed by registering plugins which the MSCRM framework executes on certain events. The problem you run into is where do you run the registration logic since there is no "startup" event that you can subscribe to for setting up your DI container. Even if you could somehow setup your DI you would need to put the CSL and the DI libraries in the GAC since that is the only way to call out to 3rd party code from a plugin (one more item to add to your deployment checklist).
In scenarios such as this you are better off having your dependencies as constructor parameters that the calling code can initialize as it sees fit( via either constructor injection or manually "newing" up the appropriate interface implementation).

Categories

Resources