[英]Autofac and open generics
Is it possible to get this scenario to work?是否有可能使这种情况起作用?
[TestFixture]
public class AutofacTests
{
private IContainer _container;
public AutofacTests()
{
var builder = new ContainerBuilder();
builder.RegisterType<Command1>();
builder.RegisterType<Command2>();
builder.RegisterType<CommandHandler1>();
builder.RegisterType<CommandHandler2>();
builder.RegisterGeneric(typeof (IHandle<>));
_container = builder.Build();
}
[Test]
[Ignore]
public void Open_generics_test()
{
//this isn't working
CommandHandler1 commandHadler1 = _container.Resolve<IHandle<Command1>>();
CommandHandler2 commandHadler2 = _container.Resolve<IHandle<Command2>>();
}
interface IHandle<T> where T : class
{
void Handle(T command);
}
class CommandHandler1 : IHandle<Command1>
{
public void Handle(Command1 command)
{
throw new System.NotImplementedException();
}
}
class Command1{}
class CommandHandler2 : IHandle<Command2>
{
public void Handle(Command2 command)
{
throw new System.NotImplementedException();
}
}
class Command2{}
}
I'm pretty sure RegisterGeneric
requires a concrete implementation type to close over (eg Handler<T>
. I don't think you can use an interface like you have.我很确定RegisterGeneric
需要一个具体的实现类型来结束(例如Handler<T>
。我认为你不能使用像你这样的接口。
You can achieve what you want with the following alternative registration code.您可以使用以下替代注册码来实现您想要的。
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsClosedTypesOf(typeof(IHandle<>));
_container = builder.Build();
var commandHandler1 = _container.Resolve<IHandle<Command1>>();
var commandHandler2 = _container.Resolve<IHandle<Command2>>();
I have added a working version of this to AutofacAnswers on GitHub.我在GitHub上的 AutofacAnswers 中添加了一个工作版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.