我在IoC容器中出厂安装了以下组件:
// Factory for late-binding scenarios
container.AddFacility<TypedFactoryFacility>();
container.Register(
Component
.For<IServiceFactory>()
.AsFactory()
);其中,IServiceFactory是:
public interface IServiceFactory
{
T Create<T>();
void Release(object service);
}然后我的控制器看起来像这样:
public class PostsController : BaseController
{
private readonly IServiceFactory serviceFactory;
private LinkService linkService
{
get { return serviceFactory.Create<LinkService>(); }
}
public PostsController(IServiceFactory serviceFactory)
{
if (serviceFactory == null)
{
throw new ArgumentNullException("serviceFactory");
}
this.serviceFactory = serviceFactory;
}关键是,即使LinkService有PerWebRequest的生活方式,我可能也不总是需要它,因此,直接注入它对我来说似乎是错误的。
然而,现在脑海中浮现的问题是:我是否在这里使用容器作为服务定位器?
发布于 2012-02-28 04:48:38
如果T是无界的,那么您就是无界的。您正在将类型的知识放在接收类中创建。这种配置最好留给负责设置容器的类。在Castle3.0中,您可以选择使用Lazy<T>来延迟解析,您可以在这里轻松地做到这一点:
public PostsController(Lazy<ILinkService> linkService)
{
if (linkService == null)
{
throw new ArgumentNullException("linkService");
}
this.linkService = linkService;
} 发布于 2012-02-28 04:30:37
是的,你是using the container as a Service Locator。
https://stackoverflow.com/questions/9471372
复制相似问题