Suppose I have registered a number of external dependencies from a folder using the following code:
container.Register(Types.FromAssemblyInDirectory(new AssemblyFilter(""))
.Where(a = >a.IsSubclassOf(typeof(MyPlugin))));
The code above works fine and I'm able to see all dependencies inheriting MyPlugin
in the container. Say I have the classes MyPluginA
and MyPluginB
inheriting from MyPlugin
in the container and I would like to retrieve MyPluginA
. How should I go about it?
Thanks
The usual method is to register each implementation with a name, and resolve them using the name. This is how I've done it in the past.
To register plugins in their installers:
container.Register(
Component.For<MyPlugin>.Named(MyPluginA.ID).ImplementedBy<MyPluginA>());
ID could be the name of the class, or any unique string ID. To resolve, you get Windsor to implement you a factory that can accept an ID. Define the interface:
public interface IPluginFactory
{
MyPlugin CreatePluginById(String id);
}
Define a component selector that can select plugin IDs provided as the first argument in a constructor:
public class PluginFactorySelector : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return (method.Name.EndsWith("ById") && arguments.Length >= 1 && arguments[0] is string)
? (string) arguments[0]
: base.GetComponentName(method, arguments);
}
}
Finally, hook it all up in an installer in your application...
container.Register(
Component.For<PluginFactorySelector, ITypedFactoryComponentSelector>().LifestyleSingleton(),
Component.For<IPluginFactory>().AsFactory(c => c.SelectedWith<PluginFactorySelector>()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.