【发布时间】: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");
}
【问题讨论】:
-
您可能对这个问题感兴趣:stackoverflow.com/questions/5026711/…
标签: c# .net dependency-injection ioc-container spring.net