0

我需要在Migrations \ Configuration.cs中使用依赖注入,以从我的服务层为种子赋值。我使用Unity来做到这一点。我的Unity容器在整个网站中工作正常,因为我通过构造类实例化了所有的接口。但是我不能在Configuration.cs文件中这样做,因为Code First使用空的构造函数。如何从迁移代码中首次使用依赖注入与Unity?

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

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,Culture = neutral, PublicKeyToken = 31bf3856ad364e35'未标记为可序列化。

感谢,

大卫

回答

0

我不知道团结,但你的问题是一种常见的DI模式。

恕我直言,这个问题是你通过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>(); 

在幕后,统一容器首先构造GenderService对象,然后将它传递给Configuration类的构造函数 。