StructureMap单例因参数而异吗?

Chr*_*tow 4 .net structuremap asp.net-mvc dependency-injection inversion-of-control

使用StructureMap,是否可以为参数的每个值设置一个单独的对象?例如,假设我想为多租户网络应用中的每个网站维护一个不同的单例:

For<ISiteSettings>().Singleton().Use<SiteSettings>();
Run Code Online (Sandbox Code Playgroud)

我想维护一个与每个站点对应的不同单例对象:

ObjectFactory.With<string>(requestHost).GetInstance<ISiteSettings>();
Run Code Online (Sandbox Code Playgroud)

目前,每当我尝试解析ISiteSettings时,它似乎都会创建一个新对象.

Chr*_*tow 5

谢谢约书亚,我接受了你的建议.这是我完成的解决方案,似乎工作正常.任何反馈意见.

public class TenantLifecycle : ILifecycle
{
    private readonly ConcurrentDictionary<string, MainObjectCache> _tenantCaches =
        new ConcurrentDictionary<string, MainObjectCache>();

    public IObjectCache FindCache()
    {
        var cache = _tenantCaches.GetOrAdd(TenantKey, new MainObjectCache());
        return cache;
    }

    public void EjectAll()
    {
        FindCache().DisposeAndClear();
    }

    public string Scope
    {
        get { return "Tenant"; }
    }

    protected virtual string TenantKey
    {
        get
        {
            var requestHost = HttpContext.Current.Request.Url.Host;
            var normalisedRequestHost = requestHost.ToLowerInvariant();
            return normalisedRequestHost;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用StructureMap配置:

ObjectFactory.Initialize(
    x => x.For<ISiteSettings>()
        .LifecycleIs(new TenantLifecycle())
        .Use<SiteSettings>()
);
Run Code Online (Sandbox Code Playgroud)