IoC实践--用Autofac实现MVC5.0的IoC控制反转方法



Autofac是一个.net平台下发性能还不错的IoC框架,利用它可以实现依赖注入和控制反转,使自己的软件模块之间的耦合性大大降低,让软件扩展、维护更加容易。控制反转(Inversion of Control,英文缩写为IoC)是一个重要的面向对象编程的法则来削减计算机程序的耦合问题。下面我就用Autofac实现ASP.NET mvc5.0的IOC控制反转的方法。这里用到是vs2013,Autofac ASP.NET MVC 5 Integration和mvc 5.0。Autofac ASP.NET MVC 5 Integration是Autofac的MVC封装库,我们只需要很少的代码就可以实现依赖注入。下面请看详细实例。

1、下载安装相关代码

在你的web项目右键选择“管理nuget程序包”

 

选中左边的联机,然后在搜索的输入框输入“autofac”

选中Autofac ASP.NET MVC 5 Integration,点击安装,这样你的项目就下载Autofac ASP.NET MVC 5 Integration了这个相关的dll的引用,并自动给添加了相关引用。

2、案例展示

定义一个业务接口IProductRepository,用来获取所有产品 
public interface IProductRepository
 {
        IQueryable<Product> Products { get; }
}

 

定义一个业务具体类,实现IProductRepository接口
复制代码
public class EFProductRepository : IProductRepository
 {
        private EFDbContext context = new EFDbContext();
        public IQueryable<Product> Products
        {
            get { return context.Products; }
        }
}
复制代码

 

EFDbContext定义的EF类,我这里是用EF框架来实现读取数据库记录,当然你可以用纯的ADO、或者其它框架如ibatis.Net、Nhibernate、 dapper等。

 2.1、定义一个Controller依赖IProductRepository接口

复制代码
public class BuyController : Controller
{
 private IProductRepository repository;
 public BuyController(IProductRepository repo)
 {
  repository = repo;
 }
 
    //此处省略其它代码
}
复制代码

 

2.2、绑定IProductRepository接口依赖的具体实现的类

复制代码
using Autofac;
using Autofac.Integration.Mvc;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.linq;
using System.Web;
using System.Web.Mvc;
using WenMarine.BLL.Abstract;
using WenMarine.BLL.Concrete;
using WenMarine.Web.Infrastructure.Abstract;
using WenMarine.Web.Infrastructure.Concrete;
namespace WenMarine.Web.Infrastructure
{
    public class IocConfig
    {
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
           builder.RegisterType<EFProductRepository>().As<IProductRepository>(); 
              
            //autofac 注册依赖
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}
复制代码

 

 

2.3、调用IocConfig使依赖生效

复制代码
protected void Application_Start()
{
 AreaRegistration.RegisterAllAreas();
 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
 RouteConfig.RegisterRoutes(RouteTable.Routes);
 BundleConfig.RegisterBundles(BundleTable.Bundles);
 IocConfig.RegisterDependencies();
}
复制代码

 

 

3、总结

通过上面可以看到,BuyController(高层模块)中是引用一个IProductRepository抽象接口而不是具体的实现EFProductRepository(具体模块)类。这样做到依赖倒置,也就是控制反转。这里高层模块(BuyController)不依赖于底层模块(EFProductRepository里面的读取数据库操作的低层代码),二者都同依赖于抽象(IProductRepository);抽象不依赖于具体(EFProductRepository),具体依赖于抽象。
这里BuyController中的IProductRepository到底是哪个实现,是通过IocConfig类使用autofac的来注册绑定的。这样如果以后要更改数据库读取方式,考虑到性能问题,比如不用EF了框架了,要用Dapper,直接新建一个类DapperProductRepository继承IProductRepository接口,实现Products 属性。
最后把IocConfig中builder.RegisterType<EFProductRepository>().As<IProductRepository>(); 
改为
builder.RegisterType<DapperProductRepository >().As<IProductRepository>(); 

就可以了。这样BuyController高层的代码根本不用改,这样做到了对扩展开发,对修改关闭(OCP-面向对象的开放封闭原则),这个是面向对象程序设计的核心。很好的做到的松耦合,模块之间的耦合性大大降低,让软件扩展、维护更加容易。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 MVC5 中使用 Autofac 实现配置文件注入,可以使用 Autofac Configuration 扩展,它可以从配置文件中读取依赖项并将它们注册到容器中。 以下是实现配置文件注入的步骤: 1. 安装 Autofac.Configuration NuGet 包。 2. 创建一个名为 AutofacConfig 的类来注册依赖项。在 Register 方法中,使用 ConfigurationModule.Register 方法注册配置文件。 3. 在 Global.asax.cs 文件中的 Application_Start 方法中,调用 AutofacConfig 类的 Register 方法,并将其传递给一个新的 ContainerBuilder 对象。 4. 在 Global.asax.cs 文件中的 Application_EndRequest 方法中,调用 AutofacDependencyResolver 类的 Dispose 方法以清理依赖项。 下面是一个示例 AutofacConfig 类,用于在 MVC5 中实现配置文件注入: ```csharp using Autofac; using Autofac.Configuration; using System.Configuration; using System.Web.Mvc; public class AutofacConfig { public static void Register(ContainerBuilder builder) { var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var module = new ConfigurationModule(config); builder.RegisterModule(module); builder.RegisterControllers(typeof(MvcApplication).Assembly); } } ``` 在 Global.asax.cs 文件中,可以像这样调用 AutofacConfig 类的 Register 方法: ```csharp protected void Application_Start() { var builder = new ContainerBuilder(); AutofacConfig.Register(builder); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); // ... } ``` 然后,在 Global.asax.cs 文件中的 Application_EndRequest 方法中,可以像这样调用 AutofacDependencyResolver 类的 Dispose 方法: ```csharp protected void Application_EndRequest() { var resolver = DependencyResolver.Current as AutofacDependencyResolver; if (resolver != null) { resolver.Dispose(); } } ``` 现在,可以在 app.config 或 web.config 文件中定义依赖项。例如: ```xml <autofac> <components> <component type="MyService" service="IMyService"> <parameters> <parameter name="myDependency" type="MyDependency" /> </parameters> </component> <component type="MyDependency" service="IMyDependency" /> </components> </autofac> ``` 在这个例子中,MyService 类取决于 MyDependency 类。当容器构建时,Autofac 会读取配置文件并注册 MyService 和 MyDependency 类。注意,service 属性指定了接口类型,而 type 属性指定了实现类型。 以上就是使用 Autofac 实现配置文件注入的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值