Injecting a specific instance of an interface using Autofac

浪尽此生 提交于 2019-12-05 18:34:44

IIRC:

builder.RegisterType<MyClassB>().As<IMyInterface>()

Update

Ok. Misread your question.

Actually, you should never ever do what you are asking. It's bound to give you problems. Why? Since there is no way to determine that the controllers can not work with the same interface. Amongst others, you are breaking the Liskovs Substitution Principle. It might not be a problem for you now, but let your application grow and come back in a year and try to understand why it isn't working.

Instead, create two new interfaces which derive from `IMyInterface´ and request those in the controllers.

Update 2

Qouting snowbear:

I disagree. OP doesn't says that his controller cannot work with instance of another type, he says that he wants to inject instances of different types. Let's imagine he has some service to extract data and he has a service which wraps this data service and provides caching functionality. I believe they should have the same interface in such situation and it is matter of DI to inject correct service

OP says just that: Controller A cannot work same class as controller B. Why would he else want to get different classes in different controllers for the same interface?

Brendan:

I personally would create a INewsMapper interface to make everything clear and sound. But if you do not want to do that: Go for a generic interface with the aggregate root as type parameter.

public interface IMapper<T> : IMapper where T : class
{

}

public class NewsMapper : IMapper<News>
{
   static NewsMapper()
   {
      Mapper.CreateMap<News, NewsEditViewData>();
      Mapper.CreateMap<NewsEditViewData, News>();
   }

   public object Map(object source, Type sourceType, Type destinationType)
   {
      return Mapper.Map(source, sourceType, destinationType);
   }
}

public NewsController(INewsService newsService, IMapper<News> newsMapper)
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!