castle: register interface proxies by convention
-
01-07-2021 - |
質問
I want to register multiple components implementing the dictionary adapter, but the AllTypes.From.. only picks class-types. I want to do something like this:
container.Register(AllTypes.FromAssemblyContaining<IFooSettings>()
.Where(type => type.IsInterface)
.Configure(component =>
component.UsingFactoryMethod((kernel, model, creationContext) => new DictionaryAdapterFactory().GetAdapter(creationContext.RequestedType, ConfigurationManager.AppSettings))));
Now I can't seem to be able to create my own version of "AllTypes" since the FromTypesDescriptor ctor is internal. Any ideas how I can accomplish this?
解決
This now works in Castle 3.3.0:
var dictionaryAdapterFactory = new DictionaryAdapterFactory();
container.Register(
Types.FromThisAssembly().Where(t => t.Name.EndsWith("Settings") && t.IsInterface)
.Configure(component => component.UsingFactoryMethod((kernel, model, creationContext) => dictionaryAdapterFactory.GetAdapter(creationContext.RequestedType, ConfigurationManager.AppSettings))));
You have to use "Types" which also picks up interfaces
他のヒント
I do something like this
container.Register(
AllTypes
.FromThisAssembly()
.Pick()
.WithService.DefaultInterface()
.Configure(r => r.LifeStyle.Transient));
This registers components based on a matching interface and class name.
So if I ask Castle for an interface called IFooSettings
then Castle will by default return the class FooSettings
.
There are a series of rules you can use for registration and you can see them here. It's does not recommend using the Factory method you are using in your example.