場景:上Autofac定製lifetimescopes與多租戶需要指導
我需要在相同 Web應用程序(應用程序域)內提供不同接口實現對相同接口定義,但到不同的「示波器」。
想象一下,一個簡單的分層網絡的內容結構是這樣的(如果你不熟悉與SharePoint):
RootWeb (SPSite) (ctx here)
|______SubWeb1 (SPWeb) (ctx here)
|______SubWeb2 (SPWeb)
|______SubWeb3 (SPWeb)
|_______SubWeb3.1 (SPWeb) (ctx here)
|_______SubWeb3.2 (SPWeb)
RootWeb,SubWeb1 UND SubWeb3.1提供上下文。那是我實現了一個AppIsolatedContext類,該類專用於特定的層次結構級別。如果一個級別沒有提供上下文,它就會從父節點繼承上下文,依此類推。例如SubWeb3會從RootWeb繼承它的上下文。但SubWeb3.1提供了自己的獨立上下文。
孤立的上下文只是一個靜態的ConcurrentDictionary。
好吧,迄今爲止好。現在關於Autofac(我是Autofac和任何其他DI容器的新手 - 不是IoC的原理)...我不知道如何正確設置它來正確處理對象。事實上,它不應該是一個問題,因爲對象(一旦它們被創建)應該活着,直到應用程序域被回收爲止(將它們想象成「每個孤立的上下文單例」)。
我會傾向於做這樣的事情:
// For completeness.. a dummy page which creates a "dummy" context
public partial class _Default : Page
{
private static AppIsolatedContext _dummyContainer = new AppIsolatedContext();
public _Default()
{
_dummyContainer.ExceptionHandler.Execute("Test Message");
}
}
// The isolated context which holds all the "context" specific objects
public class AppIsolatedContext
{
public static IContainer Container { get; set; }
public IExceptionHandler ExceptionHandler { get; set; }
//public ISomething Something { get; set; }
//public ISomethingElse SomethingElse { get; set; }
public AppIsolatedContext()
{
// set up autofac
// Create your builder.
ContainerBuilder builder = new ContainerBuilder();
// Usually you're only interested in exposing the type
// via its interface:
builder.RegisterType<MailNotificationHandler>().As<INotificationHandler>();
builder.RegisterType<ExceptionHandler>().As<IExceptionHandler>();
Container = builder.Build();
using (ILifetimeScope scope = Container.BeginLifetimeScope())
{
ExceptionHandler = scope.Resolve<IExceptionHandler>();
//Something = scope.Resolve<ISomething>();
//SomethingElse = scope.Resolve<ISomethingElse>();
}
}
}
當然我的應用並不侷限於這些「背景下單」的情況。我會每個請求生命週期的實例..但這正是ASP.NET集成模塊在那裏的權利?我希望他們可以無縫地集成到SharePoint(2013):)
所以我的問題是是不是我提出或我需要讓我的手髒?如果是這樣一些方向將是驚人的 ...
通過Autofac的文檔,我在它的多租戶能力跌跌撞撞挖。 我相信這可能適合我的目的。任何人都可以證實這一點?
using System;
using System.Web;
using Autofac.Extras.Multitenant;
namespace DemoNamespace
{
public class RequestParameterStrategy : ITenantIdentificationStrategy
{
public bool TryIdentifyTenant(out object tenantId)
{
tenantId = AppIsolatedContext.Current.Id; // not implemented in the dummy class above, but present in the real thing.
return !string.IsNullOrWhiteSpace(tenantId);
}
}
}
如果有什麼不結晶 - 請不要猶豫,告訴我:)
謝謝你告訴我的冗長的方式我需要讓自己的手髒:)我會看看你建議給我的各種章節/實現。 儘管一個小小的音符:鑑於我總是可以得到「當前的自定義上下文ID」這樣的事實不足以支持多租戶工作嗎?對於AutoFac來說,它只是一個「ID」列表,它必須擁有不同的類型映射。 – lapsus
問題在於層次結構 - 如上所述,多租戶是FLAT,而您的站點是層次結構。它是相似的,但租戶作用域始終脫離容器,而您希望子Web作用域脫離適當的父作用域 - 而不僅僅是根容器。 –