我是一个有用的助手,可以为您翻译中文。
我有一个控制器,它接收了一个特定的接口实例。
这个接口看起来像这样:
在我的ControllerA中,我有以下构造函数:
在我的global.ascx文件中:
我指定了Autofac必须提供ICustomerService的实例。那么我如何指定IMyInterface的实例类型呢?在这种情况下,对于ControllerA,我希望Autofac注入ClassA实例。而对于ControllerB,我希望它注入ClassB。我应该怎么做呢?
更新于2011-02-14:
让我告诉你我的真实情况。我有一个NewsController,其构造函数如下:
那么,您现在会建议我怎样做呢?
我有一个控制器,它接收了一个特定的接口实例。
这个接口看起来像这样:
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-02-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);
}
我正在使用AutoMapper。因此,我的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);
}
}
那么,您现在会建议我怎样做呢?