加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 其中Simple Injector等效于StructureMap的Object

发布时间:2020-12-16 04:17:42 所属栏目:asp.Net 来源:网络整理
导读:我正在ASP.NET MVC3应用程序中从StructureMap迁移到Simple Injector. 我正在使用控制器DI的MVC3扩展,但我遇到了尝试替换StructureMap的静态方面的问题.我们有电话 StructureMap.ObjectFactory.GetInstanceInterface() 在应用程序的不同层.它看起来不像Simple
我正在ASP.NET MVC3应用程序中从StructureMap迁移到Simple Injector.

我正在使用控制器DI的MVC3扩展,但我遇到了尝试替换StructureMap的静态方面的问题.我们有电话

StructureMap.ObjectFactory.GetInstance<Interface>()

在应用程序的不同层.它看起来不像Simple Injector有办法做到这一点.

我错过了什么吗?或者Simple Injector不适用于我的应用程序?

请提前通知并表示感谢.

解决方法

允许应用程序直接访问容器被认为是不好的做法.它是 Service Locator pattern的一种形式,被认为是 anti-pattern:

In short,the problem with Service Locator is that it hides a class’
dependencies,causing run-time errors instead of compile-time errors,
as well as making the code more difficult to maintain because it
becomes unclear when you would be introducing a breaking change.

因为这被认为是一件坏事,Simple Injector不包含任何类似StructureMap的ObjectFactory.GetInstance.事实上,ObjectFactory API的StructureMap is considering the removal的作者在一个版本发布的StructureMap中.

但是,没有什么能阻止您将SimpleInjector.Container实例存储在静态字段中,并让应用程序使用它:

// Service Locator implementation in low application layer.
public static class ObjectFactory
{
    private static SimpleInjector.Container container;

    public static void SetContainer(Container container)
    {
        ObjectFactory.container = container;
    }

    public static void GetInstance<T>() where T : class
    {
        return container.GetInstance<T>();
    }
}

在Composition根目录中:

public static void Initialize()
{
   var container = new Container();      

   InitializeContainer(container);

   DependencyResolver.SetResolver(
        new SimpleInjectorDependencyResolver(container));   

   // Set the service locator here
   ObjectFactory.SetContainer(container);
}

因此,Simple Injector没有任何限制可以阻止你这样做,但坦率地说,你已经看到了Service Locator是一件坏事的原因之一:你切换了容器,现在你必须更改应用程序代码.

也许现在最简单的方法是将容器保存在静态字段中(如上例所示),但是请花时间理解为什么这种模式不好,并且重构从这种模式转向依赖注入(和特别是构造函数注入).

祝好运.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读