我需要在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始终为null,我以同样的方式得到了这个错误:
在程序集中键入“Microsoft.Practices.Unity.ResolutionFailedException” 'Microsoft.Practices.Unity,Version = 3.5.0.0,Culture = neutral, PublicKeyToken = 31bf3856ad364e35'未标记为可序列化。
感谢,
大卫
答案 0 :(得分:0)
我不认识Unity,但你的问题是常见的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>();
在幕后,Unity容器首先构造一个GenderService对象,然后将其传递给构造函数 配置类。