【问题标题】:How use Dependency Injection with Unity from Migration Code First?如何从迁移代码优先使用依赖注入和 Unity?
【发布时间】:2015-04-04 01:48:47
【问题描述】:

我需要在 Migrations\Configuration.cs 中使用依赖注入来从我的服务层播种值。我使用 Unity 来做到这一点。我的 Unity 容器在整个网站上都可以正常工作,因为我通过 Constructor 类实例化了所有接口。但我不能在 Configuration.cs 文件中这样做,因为 Code First 使用空的构造函数。

这是我的代码。告诉我我做错了什么?

internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
    {
        private IGenderService _genderService;

        public Configuration()
        {
            AutomaticMigrationsEnabled = false;

            using (var container = UnityConfig.GetConfiguredContainer())
            {
                var isRegister = container.IsRegistered<IGenderService>(); // Return true!
                _genderService = container.Resolve<IGenderService>();

                if (_genderService == null)
                    throw new Exception("Doh! Empty");
                else
                    throw new Exception("Yeah! Can continue!!");
            };
        }

        public Configuration(IGenderService genderService) // Cannot use this constructor because of Code First!!!
        {
            _genderService = genderService;
        }
}

_genderService 始终为空,我以同样的方式收到此错误:

在程序集中键入“Microsoft.Practices.Unity.ResolutionFailedException” 'Microsoft.Practices.Unity,版本=3.5.0.0,文化=中性, PublicKeyToken=31bf3856ad364e35' 未标记为可序列化。

谢谢,

大卫

【问题讨论】:

    标签: c# dependency-injection asp.net-mvc-5 entity-framework-migrations


    【解决方案1】:

    我不了解 Unity,但您的问题是常见的 DI 模式。

    恕我直言,问题是您在配置 ctor 中传递了 your ioc container around

    public Configuration()  {
      AutomaticMigrationsEnabled = false;
      using (var container = UnityConfig.GetConfiguredContainer())  {
            ....
      }
    

    你应该使用CompositionRoot:

    public class Bootstrap {
      public void Register() {
         var container = new UnityContainer();
         container.RegisterType<IGenderService, GenderService>();
         container.RegisterType<Configuration>();
    
      }
    }
    
    internal sealed class Configuration:  {
      private IGenderService _genderService;
      public Configuration(IGenderService genderService) {
         _genderService = genderService;
      }
    }
    
    ...
    // resolving
    var config = container.Resolve<Configuration>();
    

    在幕后,Unity 容器首先构造了一个 GenderService 对象,然后将其传递给 配置类。

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 2013-01-17
      • 1970-01-01
      • 2016-03-18
      • 2023-03-17
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多