Harsh
Harsh

Reputation: 33

How to use Dependency Injection (AutoFac) with Repository Pattern in C#

Everyone

I am creating a Project using the repository pattern. I am stuck while implementing Dependency Injection using Autofac Library, Please help me How to implement it in Solution.

I have created a console Library Project where I registered all my component like below

public class ServiceModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<TestService>().As<ITestService>().InstancePerLifetimeScope();

        base.Load(builder);
    }
}

But My Question How to tell MVC Project that I have registered my components, Do I need to call in Global.asax file or there is other best way to do it. I didn't find any solution that helps me to implement it Please help me out to implement it.

Github Repository Link - https://github.com/Harshk16/WebApi.

Thank you

Upvotes: 0

Views: 1900

Answers (3)

ubaldisney
ubaldisney

Reputation: 66

You can Create a Bootstrapper.cs file under the Start_App folder and paste the following code. Just replace the YOUR_REPOSITORY and YOUR_IREPOSITORY for your implementations.

public static class Bootstrapper
    {
       public static void Run()
        {
            SetAutofacContainer();
        }


    private static void SetAutofacContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());

        // Repositories
        builder.RegisterType<YOUR_REPOSITORY>().As<YOUR_IREPOSITORY>().InstancePerRequest();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
 }

In the global.asax

protected void Application_Start()
        {
            // standard code
            //....

            // Autofac and Automapper configurations
             Bootstrapper.Run();
          }
}

Upvotes: 1

Sham
Sham

Reputation: 930

You need to set the container as below in MCV application.

Refer the link https://autofaccn.readthedocs.io/en/latest/integration/mvc.html# for detailed information.

public static class IocConfigurator
{
    public static void ConfigureDependencyInjection()
    {
        var builder = new ContainerBuilder();

        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterType<Repository<Student>>().As<IRepository<Student>>();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }      
}

Upvotes: 0

Fatih
Fatih

Reputation: 810

I used Dapper in example.

Edit: Make sure you are using appropriate AutoFac MVC Integration DLL in your project.

Repository Configuration

public interface IOrmRepository
{
    IDbConnection Connection { get; }
}

public class DapperRepository : IOrmRepository
{
    private readonly IDbConnection _context;

    public DapperRepository(IDbConnection context)
    {
        _context = context;
    }

    public IDbConnection Connection
    {
        get { return _context; }
    }
}

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        this.RegisterDependencies();   // these are my dependencies
    }

    private void RegisterDependencies()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        builder.Register(ctx =>
        {
            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"];
            if (string.IsNullOrWhiteSpace(connectionString.ConnectionString))
                throw new InvalidOperationException("No ConnectionString");
            return new System.Data.SqlClient.SqlConnection(connectionString.ConnectionString);
        }).As<System.Data.IDbConnection>().InstancePerLifetimeScope();

        builder.RegisterType<DapperRepository>().As<IOrmRepository>().InstancePerLifetimeScope();

        //  Other dependencies is here

        builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
        builder.RegisterModelBinderProvider();
        builder.RegisterModule<AutofacWebTypesModule>();
        builder.RegisterSource(new ViewRegistrationSource());
        builder.RegisterFilterProvider();
        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }
}

Upvotes: 0

Related Questions