Cybercrux

Everything is achievable through technology

Dependency Injection

Autofac is an addictive Inversion of Control


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Autofac;
using System.Web.Mvc;
using Autofac.Integration.Mvc;
using DI.Data;
using DI.Service;
using DI.Models;
using System.Reflection;
namespace DI.Web.App_Start
{
// Call in Global.asax.cs file
// BootStrap.Initialize(Assembly.GetExecutingAssembly());
public static class BootStrap
{
public static void Initialize(Assembly assembly)
{
var builder = new ContainerBuilder();
//register controllers
builder.RegisterControllers(assembly);
//builder.RegisterApiControllers(assembly);
//register services
builder.RegisterAssemblyTypes(typeof(PersonService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerHttpRequest();
//register repositories
builder.RegisterAssemblyTypes(typeof(PersonRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerHttpRequest();
//register the cache service
//builder.RegisterType().As().InstancePerHttpRequest();
//register the filter providers
builder.RegisterFilterProvider();
//build the container
var container = builder.Build();
// Set the dependency resolver for Web API.
//var webApiResolver = new AutofacWebApiDependencyResolver(container);
// GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
// Set the dependency resolver for MVC.
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s