Autofac - 通过通用接口解析服务

时间:2012-02-17 09:10:05

标签: autofac

我们有以下代码

public class Handler : IHandle<ICommentInfo>{}

public class Command1 : ICommentInfo{}

public interface ICommentInfo{}

public interface IHandle<T> where T : class{}

我想解决这样的服务

var service = c.Resolve<IHandle<Command1>>();

这甚至可能吗?

我尝试了这个配置

 builder.RegisterType<Handler>().As<IHandle<ICommentInfo>>();

但我得到了这个例外

The requested service 'Icp.Test.QuerySpec.Class1+IHandle`1[[Icp.Test.QuerySpec.Class1+Command1, Icp.Test.QuerySpec, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

2 个答案:

答案 0 :(得分:0)

您为什么不想使用

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<LocalCommand>().As(typeof (ICommentInfo));
builder.RegisterType<Handler>().As(typeof(IHandle<ICommentInfo>));
var c = builder.Build();
var handler = c.Resolve<IHandle<ICommentInfo>>();

答案 1 :(得分:0)

bulider.RegisterSource(new ContravariantRegistrationSource());

切换此行为。