如何在 .NET Web 中使用 Unity 解决 API

How to resolve with Unity in .NET Web API

在 Web API 项目中使用 Unity,我以标准方式在 UnityContainer 中注册了一个对象(类型 MyService 实现 IMyService)。

public static class UnityConfig {
    public static void RegisterComponents() {
        var container = new UnityContainer();
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);

        // Register my type
        container.RegisterType<IMyService, MyService>();
    }
}

我像这样在我的 类 之一中解析对象(它不是控制器,所以我不能使用构造函数注入):

// Get object from container
var myService = (IMyService)GlobalConfiguration.Configuration.DependencyResolver
                    .GetService(typeof(IMyService));

这是正确的方法吗? 看起来很笨拙。有没有更简洁的调用方式,比如直接访问容器的Resolve<T>()方法?

(我可能在这里分裂头发,但我是将 Unity 与 Web API 结合使用的新手,并试图了解最佳实践。)

"Is that the right way"?

一般来说,如果您使用正确的 DI 原则,答案是否定的。 您所做的是要求 DependencyResolver 解析服务 IMyService。 这也称为 Hollywood Principal:不要调用容器;它会打电话给你。

这也与要求 Unity 容器解析 IMyService 没有什么不同。 IE Container.Resolve

最好的方法是使用正确的构造函数注入,如果不是属性注入或一些指定的注入模式 https://github.com/ninject/Ninject/wiki/Injection-Patterns

如果您的 DEPENDENCY 需要在许多 classes 中频繁注入,您也可以考虑使用 Ambient Container。但这种情况不太可能发生。 What is the meaning of the word ambient in this comment from CommonServiceLocator?

另请注意,使用 DependencyResolver 的 class 正在使用 DI 技术,即 .Resolve,它在 class 的外部不可见。 这也意味着该组件无法重用,因为外界无法确定它在编译时需要什么 DI。如果 DI 要求未注册则可能导致运行时错误(如果 DEPENDENCY 尚未注册)。