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.
Related
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 trying to adopt BDD in my organization and since C#.Net is our primary mode of development, Specflow is our best bet for "anything Cucumber".
However, I've been a Spring aficionado in the past, but at my company we're using Autofac for various parts of the application. However, I'm unable to find any resources that explain "how" Autofac can be used to "trigger" Specflow's BDD tests and provide the necessary wiring of dependencies.
I plan to have Autofac be responsible for instantiating, wiring and executing everything instead of executing Specflow and have methods calling Autofac littered everywhere i.e., using Autofac as a Service Locator instead of a DI/IoC Container. Can this even be done or am I looking at it the wrong way and there is a better way of achieving the same goal? Or should I purely rely on Specflow's "internal container" for DI and forget about Autofac altogether?
Possible approaches:
Have Autofac instantiate and wire everything and run Specflow tests (not sure if this is even possible/recommended).
Have Specflow globally instantiate Autofac which is wired with the necessary dependencies for the remainder of the code. Possible that step definitions may land up using Autofac as a factory to get what they need.
Pros/Cons:
The first approach is ideal since it prevents any dependencies from Specflow to Autofac. The former is oblivious of the latter. Completely transparent. Preferred, but not sure how to go about it.
The latter approach "could" work if Autofac could be globally instantiated by Specflow once for use later. But this would lead to lots of calls to Autofac from within the step definitions coupling the two libraries together. Not preferable.
I'm not sure how to achieve either of them and if it's better to let Specflow handle DI and forget about Autofac or have Autofac fire everything up or if there is some middle ground?
Current BDD setup: Specflow, Selenium/PhantomJS, Xunit. Looking to combine with Autofac.
I plan to have Autofac be responsible for instantiating, wiring and
executing everything instead of executing Specflow and have methods
calling Autofac littered everywhere.
I don't really see how you would achieve this and still be able to run your tests from Visual Studio or ReSharper (I'm assuming you don't want to lose that).
Have Specflow globally instantiate Autofac which is wired with the
necessary dependencies for the remainder of the code. Possible that
step definitions may land up using Autofac as a factory to get what
they need.
That is exactly what I am doing and what I recommend.
But this would lead to lots of calls to Autofac from within the step
definitions coupling the two libraries together.
I wouldn't recommend resolving the types you need in your Step Definition classes by calling AutoFac's methods directly. I would create a method in a base class or bind an object to specflow's mini DI Container that has said method.
What I would do is create a service locator interface named IServiceLocator (yes, I know that service locator is an antipattern)
public interface IServiceLocator
{
T Get<T>();
}
We would then create an implementation of this interface using Autofac (keep in mind that you could replace this for another implementation)
public class AutoFacServiceLocator: IServiceLocator
{
private readonly IContainer _container;
public AutoFacServiceLocator(IContainer container)
{
_container = container;
}
public T Get<T>()
{
//Here you add your resolution logic
}
}
The fact that for each scenario we need an instance of IServiceLocator, we want to be able to get it through Specflow's Context Injection.
[Binding]
public class Hooks
{
private readonly IObjectContainer _objectContainer;
public Hooks(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario]
public void RegisterServiceLocator()
{
var container = CreateContainer();
var serviceLocator = new AutoFacServiceLocator(container);
_objectContainer.RegisterInstanceAs<IServiceLocator>(serviceLocator);
}
private IContainer CreateContainer() { /*Create your container*/}
}
Finally here's the usage
[Binding]
public class Steps
{
private readonly IServiceLocator _serviceLocator;
public Steps(IServiceLocator serviceLocator)
{
_serviceLocator = serviceLocator;
}
[Given(#"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredIntoTheCalculator(int p0)
{
Foo foo = _serviceLocator.Get<Foo>();
}
}
Update:
travis-illig said in the comments below
If you go with service location, try CommonServiceLocator rather than
creating your own interface
I don't really think there would be the need to use CommonServiceLocator. The calls to your service locator should match the constructor injections in your Controllers, which means that those calls should be covered by the method Get<T>().
Quoting ctavares, one of CommonServiceLocator's developers
Should I use this library for my applications?
Typically, the answer to this question is no. Once you've decided on a
container that suits your project, there's not a whole lot of benefit
from writing your whole application in a way that can switch
containers. For libraries that must fit into other ecosystems and play
nicely with other libraries, it's an important feature, but for
applications the extra layer of abstraction really doesn't buy you
much.
CommonServiceLocator is meant for libraries and frameworks, since PhD's test project is his and his team's I wouldn't recommend introducing more dependencies.
As of SpecFlow v2.1, there is now the ability to integrate different IoC containers for dependency injection.
There is a SpecFlow.Autofac package for this already, created by Gaspar Nagy: https://github.com/gasparnagy/SpecFlow.Autofac.
Gaspar provides information on how to use this package (or to write one for a different IoC container): http://gasparnagy.com/2016/08/specflow-tips-customizing-dependency-injection-with-autofac/
In the case of Autofac, the NuGet package does the hard work for you, and you only need to provide the details of how to create the container builder:
public static class TestDependencies
{
[ScenarioDependencies]
public static ContainerBuilder CreateContainerBuilder()
{
// create container with the runtime dependencies
var builder = Dependencies.CreateContainerBuilder();
//TODO: add customizations, stubs required for testing
//auto-reg all types from our assembly
//builder.RegisterAssemblyTypes(typeof(TestDependencies).Assembly).SingleInstance();
//auto-reg all [Binding] types from our assembly
builder.RegisterTypes(typeof(TestDependencies).Assembly.GetTypes().Where(t => Attribute.IsDefined(t, typeof(BindingAttribute))).ToArray()).SingleInstance();
return builder;
}
}
(In this snippet above, Dependencies.CreateContainerBuilder() is reusing the builder from the application and them supplementing it with registrations for the testing environment. See https://github.com/gasparnagy/SpecFlow.Autofac/tree/master/sample/MyCalculator for more detail.)
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.
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.
I'm using the Unity IOC container and I'm just wondering what is the best best way to access the container for multiple classes.
Should every class have an IUnityContainer member and then pass the container in by constructor? Should there be a singleton class with an IOC container?
How about asp.net development?
Could somebody guide me in the right direction? Thanks.
IMHO it is not advisable to inject the entire container into a class or to have an application wide static IoC service locator.
You want to be able to see from the constructor of a class (lets call it Foo), what kind of services/objects it is using to get the work done. This improves clarity, testability and degubability.
Lets say Foo only needs the email service, but I pass in the whole container and somewhere in the code the email service gets resolved from the container. In this case it will be very hard to follow. Instead it is better to inject the email service directly to state Foo's dependencies clearer.
If Foo needs to create multiple instances of the email service, it is better to create and inject an EmailServiceFactory (via the IoC container), which will create the required instances on the fly.
In the latter case, Foo's dependencies are still indicated as specific as possible - only the ones, that the EmailServiceFactory can create. Had I injected the whole container, it would not be clear what services provided by it are Foo's exact dependencies.
Now, if I later want to provide different instances of the email service, I swap it out inside the EmailServiceFactory. I could swap out the whole factory as well, if all the services it creates need to be swapped (e.g. during testing).
So at the cost of creating one extra class (the factory), I get much cleaner code and won't have to worry about curious bugs that may occur when global statics are used. Additionally when supplying mocks for testing, I know exactly what mocks it needs and don't have to mock out an entire container's types.
This approach also has the advantage, that now, when a module is initialized (only applies to Prism / Modularity), it doesn't have to register all of the types of objects it supplies with the IoC container. Instead it can just register its ServiceFactory which then supplies those objects.
To be clear, the module's initialization class (implements IModule) should still receive the application wide IoC container in its constructor in order to supply services, that are consumed by other modules, but the container should not invade into the module's classes.
Finally, what we have here is another fine example of how an extra layer of indirection solves a problem.
Put the IOC container at the highest level / entry point in the process and use it to inject dependencies in everything underneath it.
you can register the container in itself and have it injected like every other dependency property, like so:
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUnityContainer>(container);
classes that need to access it will have the following property:
private IUnityContainer unityContainer;
[Dependency]
public IUnityContainer UnityContainer
{
get { return unityContainer; }
set { unityContainer = value; }
}
thus, the container is injected whenever an instance of such a class is resolved/built up.
This is more flexible as it works for multiple containers within the same application, which would not be possible with the singleton pattern.
If all of your objects need a reference to the container then you should look into reworking the code some. While still preferable to calling new everywhere it still scatters the responsibility of building your object graphs throughout your code. With that kind of usage it strikes me as being used more like a ServiceLocator instead of a IoC Container.
Another option would be using the CommonServiceLocator, although it may be a pointless indirection, you may use the ServiceLocator.Current as the instance known by all classes
I have a post on this subject at my blog where I´m using something along the lines of t3mujin answer. Feel free to use it (don´t bother that it´s sharepoint related...that doesn´t matter):
http://johanleino.spaces.live.com/blog/cns!6BE273C70C45B5D1!213.entry