我對Autofac依賴注入非常新,我得到了與我的項目相關的這些問題。我已經閱讀了很多文章,但對於我的一些問題我沒有清晰的瞭解。 Mine是.Net REST API上的服務應用程序。我正在做App_Start
模塊的實例註冊,如下所示。InstancePerLifeTimeScope和對象的生命週期
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<DCLMessengerContext>()
.As<DbContext>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<DbFactory>()
.As<IDbFactory>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(EntityBaseRepository<>))
.As(typeof(IEntityBaseRepository<>))
.InstancePerLifetimeScope();
builder.RegisterType<PersonServiceClient>()
.As<IPerfService>()
.InstancePerLifetimeScope();
builder.RegisterType<PagingServiceContractClient>()
.As<PagingServiceContract>()
.InstancePerLifetimeScope();
builder.RegisterType<MessageService>()
.As<IMessageService>()
.InstancePerLifetimeScope();
Container = builder.Build();
return Container;
}
我的服務層是「MessageService」有我在執行所有DB等一體化業務,並通過構造函數注入得到的實例。這些是我在這個實現中遇到的問題。
- 我使用
InstancePerLifeTimeScope
作爲我的所有註冊。這是正確的方法嗎?在每個控制器請求(http請求)的生命週期之後,這些實例是否會自動處理? - 我們是否需要手動實現任何這些實例上的任何
Dispose
操作? (我的代碼中沒有任何非託管對象) - 從服務方法來說,我需要使用
Task.Run()
來創建火&忘記線程。什麼是最好的方法供應實例,以防止這種火災&忘記線程?如果我使用InstancePerLifeTimeScope
,我可以看到新線程也獲得了通過服務類可用的相同實例,所以我只是在這些實例被丟棄時感到困惑?
請參閱[「應該在其標題中包含」標籤?「](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles) ,那裏的共識是「不,他們不應該」! –
感謝您對此進行更新。我希望我可以將傾斜更新爲「Autofac中的InstancePerLifeTimeScope和對象的生命週期」。另外,我希望在添加額外的標籤(不包括標題),在這種情況下「ASP.Net Web API」不會有任何問題? –
這將使一個完美的編輯! –