DotNETCore 学习笔记 依赖注入和多环境

本文介绍了ASP.NET中依赖注入的基本概念与不同生命周期的服务配置方法,并提供了使用Autofac进行依赖注入的具体实现示例。此外,还讲解了如何根据不同环境进行配置。
Dependency Injection
------------------------------------------------------------------------
ASP.NET services can be configured with the following lifetimes:

Transient
Transient lifetime services are created each time they are requested. This lifetime works best for 

lightweight, stateless services.

Scoped
Scoped lifetime services are created once per request.

Singleton
Singleton lifetime services are created the first time they are requested (or when ConfigureServices is run 

if you specify an instance there) and then every subsequent request will use the same instance. If your 

application requires singleton behavior, allowing the services container to manage the service’s lifetime 

is recommended instead of implementing the singleton design pattern and managing your object’s lifetime in 

the class yourself.

**********************************************************************************
"dependencies" : {
  "Autofac": "4.0.0",
  "Autofac.Extensions.DependencyInjection": "4.0.0"
},

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
  // add other framework services

  // Add Autofac
  var containerBuilder = new ContainerBuilder();
  containerBuilder.RegisterModule<DefaultModule>();
  containerBuilder.Populate(services);
  var container = containerBuilder.Build();
  return new AutofacServiceProvider(container);
}


public class DefaultModule : Module
{
  protected override void Load(ContainerBuilder builder)
  {
    builder.RegisterType<CharacterRepository>().As<ICharacterRepository>();
  }
}

**********************************************************************************

Working with Multiple Environments

ASPNETCORE_ENVIRONMENT:Development, Staging, and Production

env.IsEnvironment("environmentname")
or
env.EnvironmentName == "Development" 

Startup{EnvironmentName} (for example StartupDevelopment)

Configure{EnvironmentName}() ConfigureDevelopment() 

Configure{EnvironmentName}Services(). ConfigureDevelopmentServices()

 

转载于:https://www.cnblogs.com/ziranquliu/p/5872109.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值