2012-02-17 57 views
2

讓我們有下面的代碼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. 

回答

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>>(); 
0
bulider.RegisterSource(new ContravariantRegistrationSource()); 

開關行爲。