I'm new to Autofac. I'm trying to integrate autofac with asp.net mvc application with the full solution following Repository pattern
Following are the configuration that I did.
MvcProject.Website.Global.asax.cs
..Application_start() {
App_Start.AutofacConfig.ConfigureContainer();
}
MvcProject.Website.App_Start.AutofacConfig.cs
NOTE: I have registered RegisterTypes as Modules in different projects and bind them from following main config file.
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));
}
}
Then, in Application layer, Type registration done by extending Module abstract class
MvcProject.Application.ApplicationModule.cs
public class ApplicationModule : Module
{
protected override void Load(Containerbuilder builder)
{
builder.RegisterType<MyService>.InstancePerLifetimeScope();
base.Load(builder);
}
}
Then, from the controller
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);
}
}
}
My main questions are:
- to avoid Memory leak issues, do we need to define lifetime scopes (as in the above MyController's SayHello action) in MVC Controllers or is that NOT necessary for the MVC ?
- Delegating the Type Registry to individual projects using Module is the correct way or is there a better/correct way ?
- Is there a better way to get ILifetimeScope inside the MyController without passing "ILifetimeScope" parameter from Constructor of the Controller ?
Thank you in advance.