1 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超9個(gè)贊
在這個(gè)版本中仍然存在同樣的靈活性。
注入IHttpContextAccessor并且您可以訪問(wèn)您需要的內(nèi)容。
重構(gòu)靜態(tài)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;
}
}
然后服務(wù)將依賴于新的抽象
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();
}
}
您確實(shí)也應(yīng)該注入 ,MyDb但這超出了當(dāng)前問(wèn)題的范圍。
最后,您將庫(kù)配置為能夠在啟動(dòng)期間設(shè)置服務(wù)
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.
}
然后你可以在從根項(xiàng)目啟動(dòng)時(shí)調(diào)用它
public void ConfigureServices(IServiceCollection services) {
//...
services.AddMyLibrary();
//...
}
通過(guò)這些抽象和使用 DI 應(yīng)用程序部分是解耦的,可以單獨(dú)測(cè)試。
- 1 回答
- 0 關(guān)注
- 270 瀏覽
添加回答
舉報(bào)