如何使用Unity.Mvc5一次注册所有服务

时间:2019-02-08 11:45:05

标签: dependency-injection unity-container dependency-resolver

请帮助我使用Unity.Mvc5立即注册所有服务和存储库。

我现在正在使用以下方案。但这需要将每个服务和存储库都注册到统一容器中。

是否可以通过扫描程序集来注册所有服务和存储库(例如由StructureMap或Lamar提供) 还是其他的东西。

预先感谢:)。

DependencyResolver.SetResolver(new UnityDependencyResolver(container));
container.RegisterType<IAbcRepository, AbcRepository>();
container.RegisterType<IAbcService, AbcService>();

1 个答案:

答案 0 :(得分:0)

我在这里的一个问题中找到了解决方案。 下面的代码按预期工作。

这有什么缺点,将来还会出现什么问题吗?还是除此以外的注册所有存储库和服务的最佳方法?

public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            // container.RegisterType<IAbcRepository, AbcRepository>();
            // container.RegisterType<IAbcService, AbcService>();

            container.RegisterTypes(AllClasses.FromAssemblies(typeof(Repository).Assembly), WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);
            container.RegisterTypes(AllClasses.FromAssemblies(typeof(Service).Assembly), WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);
        }


        static bool IsNotificationHandler(Type type)
        {
            return type.GetInterfaces().Any(x => x.IsGenericType);
        }

        static LifetimeManager GetLifetimeManager(Type type)
        {
            return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
        }

        static string GetName(Type type)
        {
            return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
        }
    }

在大型应用程序中可以安全使用多少钱?