【问题标题】:Service Locator style lookup in Spring.Net - better ideas?Spring.Net 中的服务定位器样式查找 - 更好的想法?
【发布时间】:2011-03-30 13:26:00
【问题描述】:

当我希望只有一个对象时,我使用以下方法按类型从 Spring.Net 上下文中获取对象,因此我不需要在我的代码中放入魔术字符串。我已经看到这个区域出现在配置文件中,因为那里可能很慢。有没有更暴力和更好的方法让我这样做?

public static T Locate<T>()
{
    var objList = Context.GetObjectsOfType(typeof(T));
    if (objList.Count == 0)
        throw new Exception("No object of type: " + typeof(T).FullName + " found");
    if (objList.Count > 1)
        throw new Exception("Multiple objects of type: " + typeof(T).FullName + " found");
    T oneObj = default(T);
    foreach (DictionaryEntry e in objList)
        oneObj = (T)e.Value;
    return oneObj;
}

有时我也使用这种样式来传递运行时参数。在有人因为反模式而跳槽之前......据我所知,服务定位器类型模式是传入参数的唯一方法,其值仅在运行时才知道。

public static T Locate<T>(params object[] arguments) where T : class
{
    var objectNames = Context.GetObjectNamesForType(typeof(T));
    if (objectNames.Length == 1)
    {
        return Context.GetObject(objectNames[0], arguments) as T;
    }
    if (objectNames.Length == 0)
    {
        throw new ApplicationException("No object of type: " + typeof(T).FullName + " found");
    }
    throw new ApplicationException("Multiple objects of type: " + typeof(T).FullName + " found");
}

【问题讨论】:

标签: c# .net dependency-injection ioc-container spring.net


【解决方案1】:

如果你想使用ServiceLocator 模式,我建议你使用small project on codeplex called CommonServiceLocator。它带有一个 Spring.net 适配器实现。

这样,您的代码将不依赖于 Spring 容器,允许您根据需要使用另一个容器。

一般来说,我认为您不想从代码中过多地访问您的 IOC 容器。让容器来接线;-)。

【讨论】:

  • 我查看了 CSL 的 Spring.Net 实现的源代码,他们为定位部分做了几乎相同的事情。不过,我仍然对运行时参数感到好奇。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2019-05-24
  • 2016-04-06
相关资源
最近更新 更多