问题
I use castle windsor a lot in a project i'm working on and use decorators a little so I might have something like this in my installer
Component.For<IMyViewModelService>().ImplementedBy<MyViewModelServiceCacheDecorator>().LifestyleTransient()
Component.For<IMyViewModelService>().ImplementedBy<MyViewModelService>().LifestyleTransient()
So doing this is easy enough and works well. I started reading around the simple injector framework and I really like they way you can specifically set the decorators on open generics when using the command pattern.
https://simpleinjector.readthedocs.org/en/latest/advanced.html#decorators
Does castle windsor have any functionality that allows you to do the same thing in this declarative manner? I'm using castle windsor 3.3 and always stay with the latest.
I see this question which is kind of similar but doesn't have a full outcome registering open generic decorators for typed implementations in castle windsor
回答1:
Perhaps I'm not understanding what you're trying to do, but Castle supports open generic decorators just fine. Given these objects:
public interface IService<T>
{
void Info();
}
public class Service<T> : IService<T>
{
public void Info()
{
Console.WriteLine(GetType());
}
}
public class ServiceDecorator<T> : IService<T>
{
readonly IService<T> service;
public ServiceDecorator(IService<T> service)
{
this.service = service;
}
public void Info()
{
Console.WriteLine(GetType());
service.Info();
}
}
And this registration and resolution:
container.Register(Component.For(typeof(IService<>)).ImplementedBy(typeof(ServiceDecorator<>)));
container.Register(Component.For(typeof(IService<>)).ImplementedBy(typeof(Service<>)));
Then resolving the service and calling Info:
IService<int> service = container.Resolve<IService<int>>();
service.Info();
Will print:
Sample.ServiceDecorator`1[System.Int32]
Sample.Service`1[System.Int32]
If this is not what you're trying to do, please update your question with a more precise example.
来源:https://stackoverflow.com/questions/27093818/is-there-a-way-to-explicitly-register-open-generic-decorators-with-castle-windso