在.net core中,使用配置文件注入可以灵活的控制运行的时候用具体的实现,比如Log组件是用log4net还是用Nlog;缓存使用内存还是用Redis,比如我们在appsettings.json定义:
{
"DIServices": [
{
"serviceType": "MyCore.Infrastructure.Cache.ICacheService,MyCore.Infrastructure",
"implementationType": "MyCore.Infrastructure.Cache.DefaultRedisCache,MyCore.Infrastructure",
"lifetime": "Singleton"
},
{
"serviceType": "MyCore.Infrastructure.Logger.ILogger,MyCore.Infrastructure",
"implementationType": "MyCore.Infrastructure.Logger.NLogger,MyCore.Infrastructure",
"lifetime": "Singleton"
}
],
"SystemConfig": {
"RedisConnection": "Redis连接字符串",
"RedisInstanceName": "52jiagou:dev:",
"ConnectionString": "数据库连接字符串"
}
}在这个例子中,缓存我们将使用Redis,而log使用nlog,这些都是提前封装好的。我们在Startup.cs中的ConfigureServices方法中,实现自动注入:
var serviceList = new List<Service>();
Configuration.GetSection("DIServices").Bind(serviceList);
foreach (var service in serviceList)
{
services.Add(new ServiceDescriptor(
Type.GetType(service.ServiceType),
Type.GetType(service.ImplementationType),
service.Lifetime));
}
var systemConfig = new SystemConfig();
Configuration.GetSection("SystemConfig").Bind(systemConfig);SystemConfig.cs内容:
using System;
using System.Collections.Generic;
using System.Text;
namespace MyCore.Domain.Response.Common
{
public class SystemConfig
{
/// <summary>
/// Redis链接
/// </summary>
public static string RedisConnection { get; set; }
/// <summary>
/// Redis前缀
/// </summary>
public static string RedisInstanceName { get; set; }
/// <summary>
/// 数据库链接字符串
/// </summary>
public static string ConnectionString { get; set; }
}
}Service.cs代码如下:
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Text;
namespace MyCore.Infrastructure.Dependency
{
public class Service
{
public string ServiceType { get; set; }
public string ImplementationType { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ServiceLifetime Lifetime { get; set; }
}
}