我已經在這個主題上好幾個小時了,所以我決定編寫並尋求一些幫助。注入不同的項目/裝配
在這個論壇上已經有很多答案可以認定是解決我的問題的方法,但我無法將我腦海中的所有點連接起來;我沒有完成它。
我試圖改變一個大的MVC應用程序,從StructureMap到SimpleInjector的注入器。
我需要正確地將HttpContext的當前用戶傳遞給同一個解決方案上的另一個項目,該解決方案包含所有存儲庫和DBContext,以便在執行一些CRUD操作時可以使用/寫入它。
我明顯不明白StructureMap是如何連線的;我發現它很複雜。我有這樣的MVC項目(可以提供更多的信息,因爲有一個使用StructureMap類打):
public class GlobalRegistry : StructureMap.Registry
{
public GlobalRegistry()
{
For<INotificationRepository>().Use<NotificationRepository>();
...
,並在庫項目/類:
public class NotificationRepository : BaseRepository,INotificationRepository
{
public NotificationRepository(string userContext) : base(userContext) { }
(由...魔術......)構造函數會在被調用的方法中使用userContext參數。
用SimpleInjector替換後,我不明白這個參數如何被注入。
出於測試目的,這個工程:
container.Register<INotificationRepository>(() => new NotificationRepository("username"),
Lifestyle.Singleton);
我讀了我不應該在構造函數中注入HttpContext
,因爲它是一個運行時的變量,我明白爲什麼。
接下來我嘗試了一個IUserContextFactory
,但它也沒有工作。
同MVC項目,我有他的課:
public static class ObjectFactory
{
private static SimpleInjector.Container _container;
public static void SetContainer(Container container)
{
ObjectFactory._container = container;
}
public static T GetInstance<T>() where T : class
{
return _container.GetInstance<T>();
}
}
我使用這個類來存儲容器後container.Verify();
ObjectFactory.SetContainer(container);
在任何一個MVC控制器,我使用它像這樣:
IUserContext ctxUser = ObjectFactory.GetInstance<IUserContext>();
我也試過類似下面的資料庫中的東西,嘗試,但我總是以空UserName
結束。
public NotificationRepository(IUserContext userContext) : base(userContext) { }
public interface IUserContext
{
string Username { get; set; }
}
比知道該解決方案更重要的是(MVC項目和庫項目之間共用接口),我想了解解決方案的工作,克服我一直有難度在過去的幾個小時試圖理解和解決這個問題。
那麼,還應該在'StructureMap'中對上下文進行註冊,並將其轉換爲其他語法。順便說一句,這個'Lifestyle.Singleton'看起來不太好。 –
我不明白你的實際問題是什麼,你卡在哪裏以及你想了解什麼。 – Steven
@Gert Arnold,沒有找到正在注入的StructureMap的上下文。 當用戶登錄時它保持不變,直到它註銷,我在哪裏丟失了什麼?多個用戶!? – chapas