Hi have the following component registered into Castle Windsor:
public class CommandDispatcher : IServiceCommandDispatcher
{
private readonly IWindsorContainer container;
public CommandDispatcher(IWindsorContainer container)
{
this.container = container;
}
#region IServiceCommandDispatcher Members
public void Dispatch<TCommand>(TCommand command) where TCommand : IServiceCommand
{
var handler = container.Resolve<IServiceCommandHandler<TCommand>>();
handler.Handle(command);
}
#endregion
}
And the dispatcher is registered in the following way:
Component
.For<IServiceCommandDispatcher>()
.ImplementedBy<CommandDispatcher>(),
But the field container is null when I resolve an instance of the dispatcher.
What should I do in order to pass the container to the resolved children items?
Windsor solves this problem for you with the Typed Factory Facility.
In the below example I want the implementation of ICommandHandlerFactory to resolve my command handler from my windsor container.
class CommandDispatcher : IServiceCommandDispatcher
{
private readonly ICommandHandlerFactory factory;
public CommandDispatcher(ICommandHandlerFactory factory)
{
this.factory = factory;
}
public void Dispatch<T>(T command) where T : IServiceCommand
{
var handler = this.factory.Create(command);
handler.Handle(command);
this.factory.Destroy(handler);
}
}
To achieve this I only need to create the ICommandHandlerFactory Interface.
public interface ICommandHandlerFactory
{
Handles<T> Create<T>(T command) where T : IServiceCommand;
void Destroy(object handler);
}
No implementation of ICommandHandlerFactory is required as Windsor will create the implementation. Windsor uses the convention that a method that returns an object is a resolve method and a method that returns void is a release method.
To register the factory you need to include using Castle.Facilities.TypedFactory and then register your factory as follows
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component.For<ICommandHandlerFactory>()
.AsFactory()
);
Just to reiterate you do not have to write any implementation code for your factory.
This works:
container.Register(Component.For<IWindsorContainer>().Instance(container));
It's not ideal, because you still have to call the Resolve method. There may be a better way to do this, using a factory. This looks similar to what you're trying to do:
http://kozmic.net/2010/03/11/advanced-castle-windsor-ndash-generic-typed-factories-auto-release-and-more/
Related
I'm using Castle Windsor as DI Container and have following question:
Is it possible to get informed by the container each time, any object was created by the container and get a reference to this object?
I want to check after each resolve, if the resolved object implements a special interface (e.g. IEmergencyStop). I want to register this object at a special service (EmergencyStopHelper).
Following an example:
interface IEmergencyStop
{
void Stop();
}
interface IMotor : IEmergencyStop
{
void Run();
}
class Motor : IMotor
{
}
class EmergencyStopHelper
{
List<IEmergencyStop> emergencyStopList = new List<IEmergencyStop>();
public void Register(IEmergencyStop aClass)
{
emergencyStopList.Add(aClass);
}
public void StopAll() => emergencyStopList.ForEach( x => x.Stop());
}
container.Register(Component.For<IMotor>().ImplementedBy<Motor>().LifestlyleTransient());
container.Register(Component.For<EmergencyStopHelper>());
// TODO: any magic code which calls EmergencyStopHelper.Register(...)
// after following resolve
IMotor aMotor = container.Resolve<IMotor>();
var emergencyStop = container.Resolve<EmergencyStopHelper>();
emergencyStop.StopAll();
Ok so I have looked at many posts on how to get DI working with web API. Trying to do simple ctor injection. What I am pasting here works but that doesn't mean I am happy with it. If anyone has some advice please sound off.
It appears we don't have to take control over controller creation in WEB API, which makes me question the proper releasing of dependencies. I have things setup as scoped, you will see by looking at the code. We are forced to use IDependencyResolver which I think sucks but this is the only workaround I can find as no other hooks that I have tried with IControllerActivator seem to work.
SEE CODE.
public class WindsorWeApiResolver:WindsorWebApiDependencyScope,IDependencyResolver
{
private readonly IWindsorContainer _container;
public WindsorWeApiResolver(IWindsorContainer container) : base(container)
{
_container = container;
}
public IDependencyScope BeginScope()
{
return new WindsorWebApiDependencyScope(_container);
}
}
public class WindsorWebApiDependencyScope:IDependencyScope
{
private readonly IWindsorContainer _container;
private readonly IDisposable _scope;
public WindsorWebApiDependencyScope(IWindsorContainer container)
{
_container = container;
_scope = _container.BeginScope();
}
public void Dispose()
{
_scope.Dispose();
}
public object GetService(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType).Cast<object>().ToArray();
}
}
I agree that IDependencyResolver is not ideal. I tried to negate the lack of release method, without fighting MVC, by using the Typed Factory Facility for the scope. See my post here. Your controllers can take constructor args as usual.
You can find a constructor injection implementation sample:
http://nikosbaxevanis.com/2012/07/16/using-the-web-api-dependency-resolver-with-castle-windsor-scoped-lifetime/
How can i produce the same output as specified below using the TypedFactoryFacility?
public class Something
{
public void Initialize(Whatever instance) {}
}
public interface ISomethingFactory
{
Something Create(Whatever instance);
}
internal class SomethingFactory : ISomethingFactory
{
private readonly IWindsorContainer _container;
public SomethingFactory(IWindsorContainer container)
{
_container = container;
}
public Something Create(Whatever instance)
{
Something item = _container.Resolve<Something>();
item.Initialize(instance);
return item;
}
}
So I want to replace the manual factory with a proxy-generated ITypedFactoryFacility, but I cant find a way to invoke something on the resolved component after creation. I looked at commission-concerns, but you don't have a reference to the CreationContext from a custom commision concern so that won't work. I could of course move the dependency to the ctor and provide an ctor override, but I think properties are good when you want to convey non-optional dependencies.
You don't need to invoke stuff on the instance upon creation - Windsor will automagically inject stuff when the name of the parameter in the factory method signature matches something that can be injected - be it constructor paramaters or public properties... short example (using a public property):
interface ISomeFactory
{
Something CreateSomething(object dataSource);
}
class Something
{
public object DataSource { get; set; }
}
Given that these are registered like this:
container.Register(Component.For<ISomeFactory>().AsFactory(),
Component.For<Something>().Lifestyle.Transient)
you can resolve instances of Something like this:
var aintThatSomething = someFactory.CreateSomething(new [] {"ZOMG!", "w00t!"});
Remember that if something inside the burden associated with the instance of Something requires decommissioning, you need to provide an appropriate Release method on the factory as well.
In MEF it's possible to set the dependencies for an existing object using something like:
container.SatisfyImportsOnce(instance);
Is it possible to do the same with Castle Windsor?
I'm using (read: learning) Caliburn.Micro, and trying to update the template project from MEF to Windsor, which is where I've come across the issue.
Sorry Neil, Windsor doesn't have that feature
Castle Windsor FAQ
Windsor will resolve a property dependency (which it considers an optional dependency) such as an ILogger property if there is a registered component for that service. But this only happens during component activation...when the component is constructed the first time, there is no way to pass Windsor an existing instance and inject components into properties.
With Castle Windsor you can register an existing instance with the container, is this the kind of thing you are looking for?
var instance = new Logger();
var container = new WindsorContainer();
container.Register(Component.For<ILogger>().Instance(instance))
where
public interface ILogger
{
void LogException(Exception ex);
}
public class Logger : ILogger
{
public void LogException(Exception ex)
{
// Log exception
}
}
You can however code this functionality yourself. For example, here is an ASP.NET MVC FilterAttributeFilterProvider, used to inject proprties onto attribute action filters.
public class AttributeFilterProvider : FilterAttributeFilterProvider
{
public AttributeFilterProvider(IKernel kernel)
{
_kernel = kernel;
}
private readonly IKernel _kernel;
protected override IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor);
BuildUpAttributeDependancies(attributes);
return attributes;
}
protected override IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
var attributes = base.GetActionAttributes(controllerContext, actionDescriptor);
BuildUpAttributeDependancies(attributes);
return attributes;
}
private void BuildUpAttributeDependancies(IEnumerable<FilterAttribute> attributes)
{
foreach (var attribute in attributes)
{
var propInfos = attribute.GetType().GetProperties().Where(x => x.GetValue(attribute) == null).AsEnumerable();
foreach (var pi in propInfos)
{
if (_kernel.HasComponent(pi.PropertyType))
{
var service = _kernel.Resolve(pi.PropertyType);
pi.SetValue(attribute, service);
}
}
}
}
}
In the BuildUpAttributeDependancies method, we look for un-initialised (null) properties, and then check to see if the type has been registered with Castle Windsor. If it has, we set the property.
By replacing the default FilterAttributeFilterProvider with our custom one (above) in the global.asax file we can now use Castle Windsors DI features to inject any type onto any Action Filter in our MVC application. To complete this answer fully, here is an example of a global.asax application class with Castle Windsor setup for both Controller (at instantiation time) and ActionFilter (at usage time) dependancy injection:
public class MvcApplication : System.Web.HttpApplication
{
private static IWindsorContainer _container;
private static void BootstrapContainer()
{
_container = new WindsorContainer()
.Install(FromAssembly.This());
var controllerFactory = new ControllerFactory(_container.Kernel);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
private static void BootstrapFilters()
{
var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
FilterProviders.Providers.Remove(oldProvider);
var provider = new AttributeFilterProvider(_container.Kernel);
FilterProviders.Providers.Add(provider);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
BootstrapContainer();
BootstrapFilters();
}
}
We are using the NoTrackingReleasePolicy on the Windsor container due to the memory leaks that occur when we do not Release our components after usage. Now consider the following problem.
Some disposable component:
public class DisposableComponent : IDisposable
{
private bool _disposed;
public bool Disposed
{
get { return _disposed; }
}
public void Dispose()
{
_disposed = true;
GC.SuppressFinalize(this);
}
}
Some class using the disposable component:
public class ClassWithReferenceToDisposableService
{
private DisposableComponent _disposableComponent;
public ClassWithReferenceToDisposableService(DisposableComponent disposableComponent)
{
_disposableComponent = disposableComponent;
}
}
And finaly a test which configures these components as transient and resolve/release them:
[Test]
public void ReleaseComponent_ServiceWithReferenceToTransientDisposable_TransientComponentDisposed()
{
// arrange
var windsorContainer = new WindsorContainer();
windsorContainer.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
windsorContainer.Register(Component.For<ClassWithReferenceToDisposableService>().LifeStyle.Transient);
windsorContainer.Register(Component.For<DisposableComponent>().LifeStyle.Transient);
ClassWithReferenceToDisposableService service =
windsorContainer.Resolve<ClassWithReferenceToDisposableService>();
// act
windsorContainer.Release(service);
}
Now, if I remove the NoTrackingReleasePolicy, Windsor will dispose the transient service as expected, but I can not do this (period). Now, what I want to achieve is that Windsor disposes the transient components (anywhere in the resolve graph) when I invoke ReleaseCompnent. Is there any way to achieve this without changing the NoTrackingReleasePolicy?
No, you can't have your cake and eat it too.
You can implement your own custom policy that is kind of like NoTrackingReleasePolicy but will track some components...