Autofac 和开放仿制药
这个场景有可能实现吗?
[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{}
}
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{}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很确定
RegisterGeneric
需要一个具体的实现类型来关闭(例如Handler
。我不认为你可以使用像你这样的接口。你可以使用以下替代注册代码实现您想要的效果,
我已将其工作版本添加到 AutofacAnswers 上。 GitHub。
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.
I have added a working version of this to AutofacAnswers on GitHub.