.net core中使用AutoFac(代码实例)

.net core中内置了IOC,但是内置的只能一个一个注入,效率太低,使用第三方注入包如AutoFac可以大大提高注入效率,下面开始实际应用。
一、对象的创建方式:
1.瞬时(Transient):对象总是不同的,每个控制器,每个服务提供一个新的实例。
2.作用域(Scope):每次请求的对象相同,不同请求的对象不同。
3.单例(Singleton):每个对象和每个请求都是相同的。

二、代码实例
引入nuget程序包:
Autofac
Autofac.Extensions.DependencyInjection

startup 中代码:

public static IContainer AutofacContainer;
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //注册服务进 IServiceCollection
    services.AddMvc();
    ContainerBuilder builder = new ContainerBuilder();
    //将services中的服务填充到Autofac中.
    builder.Populate(services);
    //新模块组件注册
    builder.RegisterModule<DefaultModuleRegister>();
    //创建容器.
    AutofacContainer = builder.Build();
    //使用容器创建 AutofacServiceProvider 
    return new AutofacServiceProvider(AutofacContainer);
}

上面代码调用了builder的RegisterModule函数,这个函数需要传入一个TModule的泛型,称之为autofac的模块
模块的功能就是把所有相关的注册配置都放在一个类中,使代码更易于维护和配置,下面展示了DefaultModuleRegister中的代码
DefaultModuleRegister:

public class DefaultModuleRegister : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        //注册当前程序集中以“Ser”结尾的类,暴漏类实现的所有接口,生命周期为PerLifetimeScope
        builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Ser")).AsImplementedInterfaces().InstancePerLifetimeScope();
        builder.RegisterAssemblyTypes(System.Reflection.Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerLifetimeScope();
//注册所有"MyApp.Repository"程序集中的类
        //builder.RegisterAssemblyTypes(GetAssembly("MyApp.Repository")).AsImplementedInterfaces();
    }

public static Assembly GetAssembly(string assemblyName)
{
    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + $"{assemblyName}.dll");
    return assembly;
}

}

Configure函数中可以选择性的加上程序停止时Autofac的释放函数:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    //程序停止调用函数
    appLifetime.ApplicationStopped.Register(() => { AutofacContainer.Dispose(); });
}

Controller中代码:

private IUserSer _user;
private IUserSer _user2;
public HomeController(IUserSer user, IUserSer user2)
{
    _user = user;
    _user2 = user2;
}
public IActionResult Index()
{
    using (var scope = Startup.AutofacContainer.BeginLifetimeScope())
    {
        IConfiguration config = scope.Resolve<IConfiguration>();
        IHostingEnvironment env = scope.Resolve<IHostingEnvironment>();
    }
    string name = _user.GetName();
    string name2 = _user2.GetName();
    return View();
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值