我是Autofac的新手。 我正在尝试将autofac与asp.net mvc应用程序集成在Repository模式之后的完整解决方案
以下是我所做的配置。
MvcProject.Website.Global.asax.cs
..Application_start() {
App_Start.AutofacConfig.ConfigureContainer();
}
MvcProject.Website.App_Start.AutofacConfig.cs
注意:我已将RegisterTypes注册为不同项目中的模块,并将其与以下主配置文件绑定。
public static class AutofacConfig
{
public static void ConfigureContainer()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
//Register Repository dependencies
builder.RegisterModule(new RepositoryModule("mssql"));
//Register Application dependencies
builder.RegisterModule(new ApplicationModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
然后,在Application层中,通过扩展Module抽象类
来完成类型注册MvcProject.Application.ApplicationModule.cs
public class ApplicationModule : Module
{
protected override void Load(Containerbuilder builder)
{
builder.RegisterType<MyService>.InstancePerLifetimeScope();
base.Load(builder);
}
}
然后,从控制器
MvcProject.Website.Controllers.MyController.cs
public class MyController : Controller
{
private ILifetimeScope _scope;
public MyController(ILifetimeScope scope)
{
_scope = scope;
}
public ActionResult SayHello()
{
using (var localscope = _scope.BeginLifetimeScope())
{
var service = localscope.Resolve<MyService>();
var viewModel = service.GetMyViewModel();
return View(viewModel);
}
}
}
我的主要问题是:
提前谢谢。
答案 0 :(得分:2)
我猜你已经查看了Autofac文档,了解了how to integrate with MVC和how lifetime scopes work之类的一些示例和解释,所以我会简短地说明一下:<\ n / p>
ILifetimeScope
。只需将控制器的构造函数中的依赖项与任何其他控制反转/依赖注入方案一样。如果您想推迟解析服务(就像您可能不需要那样),那么look at things like the Func<T>
relationship that Autofac supports。