如何在C#中将依赖注入(AutoFac)与存储库模式一起使用

时间:2018-10-02 10:15:43

标签: c# entity-framework model-view-controller dependency-injection inversion-of-control

所有人

我正在使用存储库模式创建一个Project。使用Autofac库实施依赖关系注入时遇到麻烦,请帮助我如何在解决方案中实现它。

我创建了一个控制台库项目,在其中注册了所有如下所示的组件

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

        base.Load(builder);
    }
}

但是我的问题如何告诉MVC Project我已经注册了组件, 我需要在Global.asax文件中调用还是有其他最佳方法。 我没有找到任何可以帮助我实现它的解决方案 请帮我实施它。

Github存储库链接-https://github.com/Harshk16/WebApi

谢谢

3 个答案:

答案 0 :(得分:1)

您可以 在 Start_App 文件夹下创建Bootstrapper.cs文件,然后粘贴以下代码。 只需为您的实现替换YOUR_REPOSITORY和YOUR_IREPOSITORY。

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));
    }
 }

在global.asax中

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

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

答案 1 :(得分:0)

您需要在MCV应用程序中按如下所示设置容器。

请参阅链接https://autofaccn.readthedocs.io/en/latest/integration/mvc.html#,以获取详细信息。

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));
    }      
}

答案 2 :(得分:0)

我以Dapper为例。

编辑:确保在项目中使用了适当的AutoFac MVC集成DLL。

存储库配置

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));
    }
}