Autofac - разрешать сервисы по универсальному интерфейсу - PullRequest
2 голосов
/ 17 февраля 2012

Давайте иметь следующий код

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 голосов
/ 21 февраля 2012
bulider.RegisterSource(new ContravariantRegistrationSource());

Включает это поведение.

0 голосов
/ 21 февраля 2012

Почему вы не хотите использовать

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>>();
...