Guys I need your help I am using Castle Project Windsor IoC container in my C# Winforms application. I have services classes which has DI by constructor passing in implementing Repositories. I used Windsor to register them all Component.Register(...etc but everytime I use my service class I am calling resolve. for example:
var employeeService = container.Resolve....etc
is there any other way not having to call resolve all the time?
in ASP.NET you can just register them all then set the Controller factory: ControllerBuilder.Current.SetControllerFactory(new WindsorIoCFactory());
with this I can just use my controllers(using services) directly without calling resolve. how do you do this in winforms?
You should use a Composition Root approach.
In short, you should use Resolve only once at the App-StartUp basically resolving the MainView and through that you should be able to obtain all views(most likely through a TypedFactory) and their dependencies with no explicit Resolve call.
Service locator approach, as per comment link, is a deprecable anti-pattern specially when Composition Root can be used instead.
On the windsor wiki you'll find a sample based on a Silverlight app, very close to a Winform scenario.
Related
I'm writing the Windows service Listner for Active MQ. I'm trying to implement Dependency Injection in the project. But i'm not sure where to register Container and how it will be resolved ?
I tried to put it in OnStart method as below, but no luck.
protected override void OnStart(string[] args)
{
container = new WindsorContainer();
// IWindsorContainer container = new WindsorContainer();
//container.Install(FromAssembly.This());
container.Register(
Component.For<IHttpClientProxyHandler>().ImplementedBy<HttpClientProxyHandlerWeb>().LifestyleTransient(),
Component.For<IHttpClientProxy>().ImplementedBy<HttpClientProxyWeb>().LifestyleTransient(),
//Component.For<IRedisCacheClient>().ImplementedBy<RedisCacheClient>().LifestyleTransient(),
Component.For<IApplicationSettings>().ImplementedBy<ApplicationSettings>().LifeStyle.PerWebRequest,
Component.For<ILogger>().ImplementedBy<Logger>().LifeStyle.PerWebRequest
);
this.messagingQueue = new ActiveMessagingQueue(new ApplicationSettings(), new Logger());
this.logger = new Logger();
this.applicationSettings = new ApplicationSettings();
this.httpClientProxyHandler = container.Resolve<IHttpClientProxyHandler>();
this.messagingQueue.OnMessageReceived += this.OnListenerMessage;
}
Then i tried to put in ServiceBase Constructor- no luck . Even tried putting it in Main function. But im getting below error always in event logger.
'Namespace.HttpClient.HttpClientProxyHandler' is waiting for the following dependencies:
- Service 'Castle.Windsor.IWindsorContainer' which was not registered.
Can anyone help here?
I agree with Patrick that you shouldn't be depending on IWindsorContainer (or IKernel) in your registered components. Instead, depend on the components (or rather, the interfaces those components implement) you need, make sure they're also registered in your container, and let Castle Windsor resolve the whole dependency hierarchy for you.
Why shouldn't you provide a mechanism for resolving dependencies to each component? Well, it hides the actual dependencies of your component and makes mocking/stubbing them in tests more difficult as you have to mock the service locator and the actual dependency. It also pushes responsibility for the management of dependencies on to you; In Castle Windsor if you explicitly Resolve a component it's best practice to also Release it when you're finished. Finally it couples your components to the particular flavour of Dependency Injection you're currently using, I.E. Castle Windsor.
I would recommend implement it together with Topshelf framework. You can see similar example here:
https://github.com/EasyNetQ/EasyNetQ/wiki/Wiring-up-EasyNetQ-with-TopShelf-and-Windsor
Instead of ActiveMQ they use EasyNetQ, but basically the problem should be the same.
Recently I came across this discussion.
In ASP.NET WebAPI, when we need to integrate a custom inversion of control/dependency injection container, we need to go with two different strategies:
Implement IHttpControllerActivator, which is an extension point to fully control controller's life-cycle. That is, we can define how a controller is instantiated. At this point, we can resolve the controller using an inversion of control container and let it use its own dependency injection approach.
Implement IDependencyResolver, where we can define how to resolve dependency injections.
In my current projects I went the IHttpControllerActivator way, and since I'm using Castle Windsor as inversion of control container, I can fully control object life cycle from its container configuration, and I can decide how controllers are resolved, and the scope of its recursively-injected dependencies defining that they die once the controller ends its life (i.e. when the request ends).
While some of these features can be achieved with IDependencyResolver implementations, I feel that IHttpControllerActivator is the best way to integrate inversion of control and dependency injection in ASP.NET Web API, because I believe that I prefer to stay as abstract as possible and stick with Castle Windsor configuration model in terms of inversion of control and dependency injection.
The main drawback with the IHttpControllerActivator approach is you need to register all controllers in the container while IDependencyResolver still gives the responsibility of resolving the controller to ASP.NET Web API pipeline (for me, this hasn't been a big issue, I just used Castle Windsor's Classes.FromAssembly to configure all controllers deriving ApiController).
Do I ignore any other drawbacks that would make the IDependencyResolver approach more appropiate?
The IHttpControllerActivator approach primarily has an advantage over the IDependencyResolver approach because of the context provided, as excellently described in the following blog post: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI/.
However, in most easier scenarios, it simply does not pay back the extra effort to manually register everything. Using the IDependencyResolver approach in many situations just 'does the trick'. Add good documentation and the larger day to day user base to that, and I myself would probably consider if I could manage using IDependencyResolver before considering IHttpControllerActivator.
I am currently using Simple Injector to resolve dependencies into my Asp.Net Web Api projects.
From the documentation you can configure it like that:
protected void Application_Start() {
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
// Here your usual Web API configuration stuff.
}
The main points here are to register the Web Api controllers and set a custom dependency resolver.
However I've just read these article from Mark Seemann on how to configure dependency injection in Asp.Net Web Api:
Dependency Injection and Lifetime Management with ASP.NET Web API
Dependency Injection in ASP.NET Web API with Castle Windsor
From these articles, I've learnt that there is a better option than implementing IDependencyResolver to resolve Web Api dependencies.
This other option is to create an implementation of the IHttpControllerActivator that acts as an Adapter over the IoC Container.
Here is the implementation I've coded using SimpleInjector:
public class SimpleInjectorControllerActivator : IHttpControllerActivator
{
private readonly Container _container;
public SimpleInjectorControllerActivator(Container container)
{
_container = container;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
request.RegisterForDispose(_container.BeginExecutionContextScope());
return (IHttpController)_container.GetInstance(controllerType);
}
}
and in the Application_Start method, I've replaced this line:
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
by this line :
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new SimpleInjectorControllerActivator(container));
I would like to know if the implementation of the IHttpControllerActivator is valid and also if this approach is valid and will work as good as the normal one ?
Yes, your implementation is valid.
Only be careful not to use both the SimpleInjectorWebApiDependencyResolver and the SimpleInjectorControllerActivator in the same application. Both start an ExecutionContextScope which could lead to having two scopes within the same web request, so they are mutually exclusive.
A general advantage of using a controller activator over the dependency resolver is that the dependency resolver contract forces the adapter to return null when a service can't be created. This is a very common problem that developers run into, and it often causes the confusing controller does not have a default constructor exception. This problem does not exist when using an IHttpControllerActivator, since the contract forces you to return a value or throw an exception.
The Simple Injector Web API integration project however, prevents this problem with dependency resolver, by never returning null (but throwing an exception instead) in case the requested service is an API controller (and thereby implicitly breaking the IDependencyResolver's contract).
An advantage of using the SimpleInjectorDependencyResolver is that it becomes easier to create message handlers that operate within the execution context scope, since you can trigger the creation of this scope by calling request.GetDependencyScope() method. With the current implementation, the scope just gets started at the time that the controller gets created, which is after you run the handlers. Changing this isn't that hard, but involves changing your controller activator and have an outermost handler that starts the execution context scope (or again falling back on a dependency resolver that manages the execution context scope).
One of the arguments of Mark Seemann is that it becomes hard to pass context around, which is a very valid point, as long as your components don't require this context during construction. But this is not a problem you'll experience when using Simple Injector, because there is an extension method that helps you with accessing the HttpRequestMessage. So although the IDependencyResolver abstraction isn't designed for getting the contextual information, there are ways to get this contextual information.
In the past we decided to go with an adapter for the IDependencyResolver, mainly because this was the common practice with all DI containers. I partly regret this decision, but using the SimpleInjectorDependencyResolver is now usually the easiest way of plugging in Simple Injector into Web API. We considered adding a SimpleInjectorControllerActivator as well, but this had no practical benefit for most users, while we still would had to document when to use what. So we decided to stick with the dependency resolver adapter; an adapter for the activator is easily created for anyone who needs it, as you can see.
For ASP.NET Core however, we went into a different direction, and as you can see in the documentation, the integration package actually contains a SimpleInjectorControllerActivator out of the box. In ASP.NET Core, the controller activator is the perfect interception point and due to the OWIN-like pipeline, a scope can be easily wrapped around a request. So with ASP.NET Core, the advised practice is to use the controller activator as interception point.
I'm working on an application that consists of many modules, with some having dependencies on other modules. I now decided to use Autofac to solve circular dependencies and improve the architecture in general.
To configure autofac I use the xml method (http://code.google.com/p/autofac/wiki/XmlConfiguration).
Now I am not sure on how to implement Autofac. Do I need to have a reference to autofac in each module in my application? Meaning that i have to register all components each time I want to solve a dependency...
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterModule(new ConfigurationSettingsReader("autofac", configPath));
IContainer container = builder.Build();
IWhatever w = container.Resolve<IWhatever>();
Is this the way to do it?
Or is it better to Wrap Autofac in a separate Module ?
With this approach I would have to register the modules only once (when the application starts) and could just use the wrapped Autofac to resolve dependencies...
IWhatever w = container.Resolve<IWhatever>();
I hope someone can tell me the best way to use Autofac.
thanks!
Each project need to have a dependency to the autofac core package if you would like to use autofac modules.
Use autofac modules as described here: http://autofac.readthedocs.io/en/latest/configuration/modules.html
Update
I describe why you should use modules here: http://www.codeproject.com/Articles/386164/Get-injected-into-the-world-of-inverted-dependenci
Separate module for container is not only a better option, it is the only right option. AFAIK IoC container instances must be singletons.
At least I've used Unity this way - you create publicly available static instance of container, initialize it on application startup and then access it from all your modules.
Is it right at all to "wrap" a StandardKernel with the required NinjectModules in a static class in a separate, shared library, and use that same library whenever injection is needed (instead of instantiating a new kernel everytime)?
Edit: I am trying to use Ninject from within the WCF service I am developing at the moment.
(Please bear with me if what I am saying is completely rubish since I just started learning about DI and IoC containers)
See https://github.com/ninject/ninject.extensions.wcf . This extension will create the WCF service using the Ninject kernel. That way you can use constructor injection instead of using the Service Locator pattern.