ASP.NET MVC 3 & Unity.MVC3(6)
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
...
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IRepository" type="GenericRepository.IRepository`1, GenericRepository" />
<alias alias="DbContextRepository" type="GenericRepository.DbContextRepository`1, GenericRepository" />
<alias alias="User" type="MvcWithUnityTest.Models.User, MvcWithUnityTest.Models" />
<alias alias="DbEntities" type="MvcWithUnityTest.Models.DbEntities, MvcWithUnityTest.Models" />
<container name="default">
<register type="IRepository[User]" mapTo="DbContextRepository[User]">
<lifetime type="HierarchicalLifetimeManager" />
<constructor>
<param name="context" dependencyType="DbEntities">
</param>
</constructor>
</register>
</container>
</unity>
</configuration>然后在 Global.asax.cs 里调用 Bootstrapper.Initialise(); 即可。
另外,需要注意的是 <register type="IRepository[User]" mapTo="DbContextRepository[User]"> 里加上了 <lifetime type="HierarchicalLifetimeManager" />
这样在 Controller 生命周期结束时才会调用 Dispose。(待展开)
再来看看 Controller 的实现:
根据上面的配置文件:<register type="IRepository[User]" mapTo="DbContextRepository[User]">
[Dependency] 标识的 UserRepository 会在 Controller 请求时被注入实例。
[csharp] print?public class HomeController : Controller
{
[Dependency]
public IRepository<User> UserRepository { get; set; }
public ActionResult Index()
{
ViewBag.Message = "ASP.NET MVC3 With Unity.MVC3!";
var users = UserRepository.GetAll();
return View(users);
相关新闻>>
- 发表评论
-
- 最新评论 更多>>