Is it possi开发者_运维技巧ble 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 (e.g. Handler<T>
. I don't think you can use an interface like you have.
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.
精彩评论