【问题标题】:StructureMap singletons varying by argument?StructureMap 单例因参数而异?
【发布时间】:2010-08-27 06:05:56
【问题描述】:

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

For<ISiteSettings>().Singleton().Use<SiteSettings>();

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

ObjectFactory.With<string>(requestHost).GetInstance<ISiteSettings>();

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

【问题讨论】:

    标签: .net asp.net-mvc dependency-injection inversion-of-control structuremap


    【解决方案1】:

    谢谢 Joshua,我接受了你的建议。这是我完成的解决方案,它似乎工作正常。任何反馈表示赞赏。

    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;
            }
        }
    }
    

    使用 StructureMap 配置:

    ObjectFactory.Initialize(
        x => x.For<ISiteSettings>()
            .LifecycleIs(new TenantLifecycle())
            .Use<SiteSettings>()
    );
    

    【讨论】:

    • 使用这个的变体,租期由查询字符串确定,效果很好。
    • 为什么 _tenantCaches 在这个实现中不是静态的?如果我在不同的“For”映射中调用 new TenantLifecycle(),我会得到新的对象缓存吗?
    【解决方案2】:

    Singleton 作用域真正的意思是单例——只能有一个实例。对于您的场景,我建议您实现一个自定义 ILifecycle,它使用 requestHost(我假设可以从 HttpContext 中提取)返回适当的缓存实例。查看 StructureMap 源代码,了解其他 ILifecycles 是如何实现的。

    当您注册For&lt;ISiteSettings&gt; 时,可以选择指定您自己的 ILifecycle,而不是使用内置的其中之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      相关资源
      最近更新 更多