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:
Thank you in advance.
I'm guessing you've already checked out the Autofac docs for some examples and explanations of things like how to integrate with MVC and how lifetime scopes work so I'll keep it short:
ILifetimeScope around in your controllers. Just take your dependencies in the constructor for the controller like any other inversion-of-control/dependency injection scenario. If you want to defer resolving a service (like you may not need it) then look at things like the Func<T> relationship that Autofac supports.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With