【发布时间】: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