容器的配置
1、配置文件
通过配置文件可以配置多个容器,通过更换 default 的值即可实现无缝切换。配置文件如下:
- .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="fireasy">
<section name="containers" type="Fireasy.Common.Ioc.Configuration.ContainerConfigurationSectionHandler, Fireasy.Common"/>
</sectionGroup>
</configSections>
<fireasy>
<containers>
<container>
<registration
serviceType="demo.IMyOneService, demo"
implementationType="demo.MyOneService, demo"
lifetime="Singleton" />
</registration>
<registration
serviceType="demo.IMyTwoService, demo"
implementationType="demo.MyTwoService, demo",
lifetime="Transient"/>
</registration>
<registration
serviceType="demo.MyThirdService, demo" />
</registration>
<registration
assembly="demo" />
</registration>
</container>
</containers>
</fireasy>
</configuration>
- .Net Core 下的 appsettings.json 文件
{
"fireasy": {
"containers": {
"settings": {
"default": [
{
"serviceType": "demo.IMyOneService, demo",
"implementationType": "demo.MyOneService, demo",
"lifetime": "Singleton" // Singleton / Transient / Scoped
},
{
"serviceType": "demo.IMyTwoService, demo",
"implementationType": "demo.MyTwoService, demo",
"lifetime": "Transient"
},
{
"serviceType": "demo.MyThirdService, demo"
},
{
"assembly": "demo"
}
]
}
}
}
}
配置节中,分别指定 serviceType(服务类/接口) 和 implementationType(实现类,当实现类和服务类是同一个时,可省略,如 MyThirdService
)。使用 assembly 可以注册整个程序集,规则见 容器的使用 -- 注册程序集。
2、.Net Core 下的配置
在 .Net Core 应用中,在 Startup.ConfigureServices 方法里,使用 AddIoc 方法将 Fireasy 的配置添加到 IServiceCollection
集合中。如下所示:
namespace demo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddFireasy(Configuration).AddIoc();
}
}
}
应用启动后,会在 输出
窗口打印出服务的注册结果。如下所示:
-->> Singleton-Descriptor has been registered: demo.IMyOneService --> demo.MyOneService.
-->> Transient-Descriptor has been registered: demo.IMyTwoService --> demo.MyTwoService.
-->> Transient-Descriptor has been registered: demo.MyThirdService --> demo.MyThirdService.