C# 如何首先从迁移代码中使用Unity的依赖项注入?
我需要在Migrations\Configuration.cs中使用依赖项注入来从我的服务层播种值。我用团结来做到这一点。我的Unity容器在整个web站点中运行良好,因为我通过构造函数类实例化了所有接口。但我不能在Configuration.cs文件中这样做,因为代码首先使用空构造函数 这是我的密码。告诉我我做错了什么C# 如何首先从迁移代码中使用Unity的依赖项注入?,c#,dependency-injection,asp.net-mvc-5,entity-framework-migrations,C#,Dependency Injection,Asp.net Mvc 5,Entity Framework Migrations,我需要在Migrations\Configuration.cs中使用依赖项注入来从我的服务层播种值。我用团结来做到这一点。我的Unity容器在整个web站点中运行良好,因为我通过构造函数类实例化了所有接口。但我不能在Configuration.cs文件中这样做,因为代码首先使用空构造函数 这是我的密码。告诉我我做错了什么 internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext&
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;
}
}
内部密封类配置:dbmigtorinsconfiguration
{
私人IGenderService(性别服务);;
公共配置()
{
AutomaticMiggerationsEnabled=假;
使用(var container=UnityConfig.GetConfiguredContainer())
{
var isRegister=container.IsRegistered();//返回true!
_genderService=container.Resolve();
if(_genderService==null)
抛出新异常(“Doh!Empty”);
其他的
抛出新异常(“耶!可以继续!!”;
};
}
公共配置(IGenderService genderService)//无法使用此构造函数,因为首先是代码!!!
{
_性别服务=性别服务;
}
}
_genderService始终为空,我以相同的方式得到此错误:
在程序集中键入“Microsoft.Practices.Unity.ResolutionFailedException”
'Microsoft.Practices.Unity,版本=3.5.0.0,区域性=中性,
PublicKeyToken=31bf3856ad364e35'未标记为可序列化
谢谢,
David我不知道Unity,但你的问题是一个常见的DI模式 问题是你通过了什么,在配置中:
public Configuration() {
AutomaticMigrationsEnabled = false;
using (var container = UnityConfig.GetConfiguredContainer()) {
....
}
您应该使用:
公共类引导{
公开作废登记册(){
var container=new UnityContainer();
container.RegisterType();
container.RegisterType();
}
}
内部密封类配置:{
私人IGenderService(性别服务);;
公共配置(IGenderService genderService){
_性别服务=性别服务;
}
}
...
//解决
var config=container.Resolve();
在幕后,Unity容器首先构造一个GenderService对象,然后将其传递给
配置类
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>();