我如何从统一容器中获取服务对象?

时间:2011-02-22 14:14:45

标签: c# asp.net-mvc

IUnityContainer unityContainer = new UnityContainer();

unityContainer.RegisterType<IMembershipService, MembershipService>();
unityContainer.RegisterInstance<IMappingEngine>(Mapper.Engine);
ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(unityContainer));

我如何获得统一容器? ControllerBuilder.Current.GetControllerFactory() - 不是。 首先我得到统一容器,从统一容器我希望使用Resolve获得服务。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

添加静态方法(请参阅GetConfiguredContainer):

public class UnityConfig
{
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    /// <returns>The generated unity container</returns>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }

    /// <summary>Registers the type mappings with the Unity container.</summary>
    /// <param name="container">The unity container to configure.</param>
    /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
    /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // Example
        container.RegisterType<IFileSystem, FileSystem>();
    }
}


var unity = new UnityConfig();
IUnityContainer unityContainer = UnityConfig.GetConfiguredContainer();

然后你可以使用:

TypeThatYouWant instance = unityContainer.Resolve<TypeThatYouWant>();

如果您无法访问UnityConfig,因为您的项目依赖项处于尴尬状态,只需在项目中为您的容器添加另一个带有静态属性的UnityConfig静态类,您需要访问它,填充它然后该项目也可以参考:

// Some other project
public static class UnityConfig
{
    public static IUnityContainer Container { get; set; }
}

var unity = new UnityConfig();
IUnityContainer unityContainer = UnityConfig.GetConfiguredContainer();

project.namespace.UnityConfig.Container = unityContainer;

除此之外,尝试设计一种可以充分利用类构造注入的设计模式。

答案 1 :(得分:-2)

你为什么这样做?它是依赖注入反模式。只需让控制器工厂通过控制器构造函数或属性注入依赖项。