1 回答
TA贡献1860条经验 获得超9个赞
在这个版本中仍然存在同样的灵活性。
注入IHttpContextAccessor并且您可以访问您需要的内容。
重构静态Auditor以使其更具可注入性
public interface IAuditor {
IAuditable Stamp(IAuditable model);
}
public class Auditor : IAuditor {
private readonly IHttpContextAccessor accessor;
public Auditor(IHttpContextAccessor accessor) {
this.accessor = accessor;
}
public IAuditable Stamp(IAuditable model){
model.CreateDate = DateTime.UtcNow;
model.CreatedBy = accessor.HttpContext.User?.Identity?.Name;
return model;
}
}
然后服务将依赖于新的抽象
public interface IMyService : IDisposable {
Task<int> Create(MyEntity model);
}
public sealed class MyService : IMyService {
MyDb db = new MyDb();
private readonly IAuditor auditor;
public MyService(IAuditor auditor) {
this.auditor = auditor;
}
public async Task<int> Create(MyEntity model) {
auditor.Stamp(model);
db.MyEntities.Add(model);
return await db.SaveAsync();
}
public void Dispose() {
db.Dispose();
}
}
您确实也应该注入 ,MyDb但这超出了当前问题的范围。
最后,您将库配置为能够在启动期间设置服务
public static IServiceCollection AddMyLibrary(this IServiceCollection services) {
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<IAuditor, Auditor>();
services.AddScoped<IMyService, MyService>();
//...add other services as needed
return services.
}
然后你可以在从根项目启动时调用它
public void ConfigureServices(IServiceCollection services) {
//...
services.AddMyLibrary();
//...
}
通过这些抽象和使用 DI 应用程序部分是解耦的,可以单独测试。
- 1 回答
- 0 关注
- 245 浏览
添加回答
举报