首先尝试通过NuGet的StructureMap和MVC3 [英] First try StructureMap and MVC3 via NuGet
问题描述
这是我从IoC Class
public static class IoC
{
public static IContainer Initialize()
{
ObjectFactory.Initialize(x => ;
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.AddAllTypesOf< ; IController>();
});
x.For&OpCio nDB>()。使用(()=> new DatabaseFactory()。Get());
});
return ObjectFactory.Container;
}
}
我的问题是为什么当我注入时会得到异常我的控制器上的一些IoC如下(我使用这种模式:实体框架4 CTP 4 / CTP 5通用存储库模式和单元可测试):
私人readonly IAsambleaRepository _aRep;
private readonly IUnitOfWork _uOw;
public AsambleaController(IAsambleaRepository aRep,IUnitOfWork uOw)
{
_aRep = aRep;
this._uOw = uOw;
}
public ActionResult List(string period)
{
var rs = _aRep.ByPeriodo(period).ToList< Asamblea>();
return View();
}
异常显示:
异常详细信息:System.MissingMethodException:为此对象定义的无参数构造函数。
您收到该错误,因为您尚未设置StructureMap来解析依赖关系需要构建 AsambleaController
,所以它试图找到一个没有参数的构造函数,没有一个。
所以你需要做的是为 IAsambleaRepository
和 IUnitOfWork
设置StructureMap。
在旁注中,我会说 IUnitOfWork
应该是依赖于你的存储库,而不是你的控制器...你的控制器应该'需要了解工作单位。
I'm trying to figure how to config StructureMap for ASP.NET MVC3 I've already using NuGet and I notice that it creates App_Start Folder with a cs file named as StructuremapMVC, so I check it and notice that is the same code but simplified that will be written manually on App_Start section placed on Global.asax...
This is my code from IoC Class
public static class IoC
{
public static IContainer Initialize()
{
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.AddAllTypesOf<IController>();
});
x.For<OpcionDB>().Use(() => new DatabaseFactory().Get());
});
return ObjectFactory.Container;
}
}
My Question is Why I get an Exception when I inject some IoC on my Controllers as the follow (I use this pattern : Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable) :
private readonly IAsambleaRepository _aRep;
private readonly IUnitOfWork _uOw;
public AsambleaController(IAsambleaRepository aRep, IUnitOfWork uOw)
{
_aRep = aRep;
this._uOw = uOw;
}
public ActionResult List(string period)
{
var rs = _aRep.ByPeriodo(period).ToList<Asamblea>();
return View();
}
Exception showed :
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
You are getting that error because you haven't setup StructureMap to resolve the dependencies needed to contruct the AsambleaController
so it tries to find a parameterless constructor which there isn't one.
So what you need to do is setup StructureMap for IAsambleaRepository
and IUnitOfWork
.
On a side note, I'd say that IUnitOfWork
should be a dependency on your repository and not your controller... your controller shouldn't need to know about the unit of work.
这篇关于首先尝试通过NuGet的StructureMap和MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!