我有一个控制器,它接收接口的特定实例。
界面看起来像这样:
public interface IMyInterface
{
... implementation goes here
}
然后我有一些类实现这个接口,如下所示:
public class MyClassA : IMyInterface
{
... implementation goes here
}
public class MyClassB : IMyInterface
{
... implementation goes here
}
在我的 ControllerA 中,我有以下构造函数:
private ICustomerService customerService;
private IMyInterface myInterface;
puvlic ControllerA(ICustomerService customerService, IMyInterface myInterface)
{
this.customerService = customerService;
this.myInterface = myInterface;
}
在我的 global.ascx 中:
protected void Application_Start()
{
// Autofac
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<NewsService>().As<INewsService>();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
我指定 Autofac 必须提供 ICustomerService 的实例。如何指定 IMyInterface 的实例类型?在这种情况下,对于 ControllerA,我希望 Autofac 注入一个 ClassA 实例。对于 ControllerB,我希望它注入 ClassB。我该怎么做?
更新于 2011 年 2 月 14 日:
让我告诉你我的真实生活情况。我有一个 NewsController ,其构造函数如下所示:
public NewsController(INewsService newsService, IMapper newsMapper)
{
Check.Argument.IsNotNull(newsService, "newsService");
Check.Argument.IsNotNull(newsMapper, "newsMapper");
this.newsService = newsService;
this.newsMapper = newsMapper;
}
IMapper接口:
public interface IMapper
{
object Map(object source, Type sourceType, Type destinationType);
}
我正在使用自动映射器。所以我的 NewsMapper 将如下所示:
public class NewsMapper : IMapper
{
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);
}
}
那么你现在会如何建议我这样做呢?