前言 一行業務代碼還沒寫,框架代碼一大堆,不利於學習。 常看到java的學習資料或博客,標題一般為《SpringBoot 整合 XXX》,所以仿照著寫了《.NET 6 整合 Autofac 依賴註入容器》這樣一個標題。 以下是我自己的用法,可能不是最佳實踐。 一. 引用包 NuGet搜索並安裝: A ...
前言
一行業務代碼還沒寫,框架代碼一大堆,不利於學習。
常看到java的學習資料或博客,標題一般為《SpringBoot 整合 XXX》,所以仿照著寫了《.NET 6 整合 Autofac 依賴註入容器》這樣一個標題。
以下是我自己的用法,可能不是最佳實踐。
一. 引用包
NuGet搜索並安裝:
Autofac
Autofac.Extensions.DependencyInjection
二. 配置代碼
var builder = WebApplication.CreateBuilder(args);
...省略
// ASP.NET Core整合Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());//通過工廠替換,把Autofac整合進來
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
ServiceFactory.SetBuilder(containerBuilder);
ServiceFactory.RegisterAssembly(Assembly.GetExecutingAssembly()); //註冊服務
});
var app = builder.Build();
ServiceFactory.SetContainer((app.Services as AutofacServiceProvider).LifetimeScope as IContainer);
Task.Run(async () => await ServiceFactory.StartAllService()); //啟動服務,註意:服務啟動完成之前,調用介面會異常
...省略
三. 服務的自動註冊、啟動、停止
IService介面
/// <summary>
/// 服務介面
/// </summary>
public interface IService
{
/// <summary>
/// 服務啟動
/// </summary>
Task OnStart();
/// <summary>
/// 服務停止
/// </summary>
Task OnStop();
}
RegisterServiceAttribute特性
/// <summary>
/// 註冊為服務
/// </summary>
public class RegisterServiceAttribute : Attribute
{
}
ServiceBase抽像類
[RegisterService]
public abstract class ServiceBase : IService
{
#region OnStart
public virtual Task OnStart()
{
return Task.CompletedTask;
}
#endregion
#region OnStop
public virtual Task OnStop()
{
return Task.CompletedTask;
}
#endregion
}
ServiceFactory服務工廠類
public class ServiceFactory
{
private static ContainerBuilder _builder;
private static IContainer _container;
private static bool _isRunning; //服務是否正在運行
public static void SetBuilder(ContainerBuilder builder)
{
_builder = builder;
}
public static void SetContainer(IContainer container)
{
_container = container;
}
/// <summary>
/// Autofac.ContainerBuilder
/// </summary>
public static ContainerBuilder Builder
{
get
{
return _builder;
}
}
/// <summary>
/// 獲取服務
/// </summary>
/// <typeparam name="T">介面類型</typeparam>
public static T Get<T>()
{
if (_isRunning)
{
return _container.Resolve<T>();
}
else
{
throw new Exception("服務尚未啟動完成");
}
}
/// <summary>
/// 獲取服務
/// </summary>
/// <param name="type">介面類型</param>
public static object Get(Type type)
{
if (_isRunning)
{
return _container.Resolve(type);
}
else
{
throw new Exception("服務尚未啟動完成");
}
}
#region 註冊程式集
/// <summary>
/// 註冊程式集
/// </summary>
/// <param name="serviceAssembly">服務程式集</param>
public static void RegisterAssembly(Assembly serviceAssembly)
{
Type[] typeArr = serviceAssembly.GetTypes();
foreach (Type type in typeArr)
{
if (type.GetCustomAttribute<RegisterServiceAttribute>() != null && !type.IsAbstract)
{
_builder.RegisterType(type).SingleInstance().AsImplementedInterfaces().AsSelf();
}
else
{
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.GetCustomAttribute<RegisterServiceAttribute>() != null && !type.IsAbstract)
{
_builder.RegisterType(type).SingleInstance().AsImplementedInterfaces().AsSelf();
break;
}
}
}
}
//_container = _builder.Build();
}
#endregion
#region 啟動所有服務
/// <summary>
/// 啟動所有服務
/// </summary>
public static async Task StartAllService()
{
Type iServiceInterfaceType = typeof(IService);
IEnumerable<Type> types = _container.ComponentRegistry.Registrations.Select(a => a.Activator.LimitType);
await Parallel.ForEachAsync(types, async (type, c) =>
{
if (iServiceInterfaceType.IsAssignableFrom(type))
{
object obj = _container.Resolve(type);
try
{
IService service = obj as IService;
await service.OnStart();
LogUtil.Info("服務 " + obj.GetType().FullName + " 已啟動");
}
catch (Exception ex)
{
LogUtil.Error(ex, "服務 " + obj.GetType().FullName + " 啟動失敗");
}
}
});
_isRunning = true;
}
#endregion
#region 停止所有服務
/// <summary>
/// 停止所有服務
/// </summary>
public static async Task StopAllService()
{
Type iServiceInterfaceType = typeof(IService);
IEnumerable<Type> types = _container.ComponentRegistry.Registrations.Select(a => a.Activator.LimitType);
await Parallel.ForEachAsync(types, async (type, c) =>
{
if (iServiceInterfaceType.IsAssignableFrom(type))
{
object obj = _container.Resolve(type);
IService service = obj as IService;
try
{
await service.OnStop();
LogUtil.Info("服務 " + obj.GetType().FullName + " 已停止");
}
catch (Exception ex)
{
LogUtil.Error(ex, "服務 " + obj.GetType().FullName + " 停止失敗");
}
}
});
_isRunning = false;
}
#endregion
}
ServiceFactory的簡寫類
/// <summary>
/// ServiceFactory的簡寫
/// </summary>
public class SF
{
/// <summary>
/// 獲取服務
/// </summary>
/// <typeparam name="T">介面類型</typeparam>
public static T Get<T>()
{
return ServiceFactory.Get<T>();
}
/// <summary>
/// 獲取服務
/// </summary>
/// <param name="type">介面類型</param>
public static object Get(Type type)
{
return ServiceFactory.Get(type);
}
}
編寫服務類
服務類示例1
/// <summary>
/// 測試服務
/// </summary>
public class TestService : ServiceBase
{
public async Task<string> GetValue()
{
return await Task.FromResult("測試數據");
}
}
服務類示例2
重寫了OnStart和OnStop以實現服務的啟動和停止。
/// <summary>
/// 定時任務管理
/// </summary>
public class ScheduleJobs : ServiceBase
{
#region 變數
private IScheduler _scheduler;
#endregion
#region OnStart
public override async Task OnStart()
{
try
{
NameValueCollection options = new NameValueCollection();
string schedulerName = "DefaultQuartzScheduler";
options.Add("quartz.scheduler.instanceName", schedulerName);
StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(options);
_scheduler = await schedulerFactory.GetScheduler(schedulerName);
if (_scheduler == null)
{
_scheduler = await schedulerFactory.GetScheduler();
}
await _scheduler.Start();
AddJobs(_scheduler);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
#endregion
#region OnStop
public override async Task OnStop()
{
await _scheduler.Shutdown();
}
#endregion
#region ScheduleJob
private async Task ScheduleJob<T>(IScheduler scheduler, string cronString) where T : IJob
{
IJobDetail jobDetail = JobBuilder.Create<T>().Build();
ITrigger trigger = TriggerBuilder.Create().WithCronSchedule(cronString).Build();
await scheduler.ScheduleJob(jobDetail, trigger);
}
#endregion
private async void AddJobs(IScheduler scheduler)
{
await ScheduleJob<TestJob>(scheduler, "0/30 * * * * ?");
}
}
構造註入示例
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly TestService _testService;
public TestController(TestService testService)
{
_testService = testService;
}
...省略
}
也可以這樣使用
var value = await SF.Get<TestService>().GetValue();