我有一个控制台应用程序,它接收一个类名并调用它的一个函数:
Assembly asm = Assembly.GetEntryAssembly();
ObjectHandle oh = Activator.CreateInstance(asm.FullName, typeName);
IScheduledTask task = (IScheduledTask)oh.Unwrap();
task.Execute();
到目前为止,除此之外不需要进行初始化,但现在我们有了一些 IScheduledTask 将通过构造函数注入依赖的组件。
有没有办法定义一个具有相同名称的类的命名实例,稍后将使用resolve解析所有依赖项?
也就是说,如果我将“SomeScheduledTask”作为参数,我可以这样做:
IScheduledTask task = (IScheduledTask)container.Resolve(typeName); // I know this is possible. The problem is the registration.
我可以做这样的事情来解决我的问题:
container.Register(Component.For<IScheduledTask>().Named(t => t.Name).Activator<MyActivator>())
在我的激活器中做这样的事情:
public class MyActivator : IComponentActivator
{
public object Create(CreationContext context)
{
string typeName = context.???; // How do I get the named instance name from here?
Assembly asm = Assembly.GetEntryAssembly();
ObjectHandle oh = Activator.CreateInstance(asm.FullName, typeName);
IScheduledTask task = (IScheduledTask)oh.Unwrap();
task.Execute();
}
public void Destroy(object instance)
{
}
}