我想创建一个可用于依赖注入的工厂对象字典.
例如,假设我有一个名为ServiceLocator的静态类.应用程序可以使用:
ITest test = ServiceLocator<ITest>.GetInstance()
Run Code Online (Sandbox Code Playgroud)
获取实现ITest接口的对象.
为了实现这一点,我首先创建了一个Interface IFactory
public interface IFactory<T>
{
T GetInstance<T>();
}
Run Code Online (Sandbox Code Playgroud)
然后,例如,ITest的具体实现可能如下所示:
public class TestFactory : IFactory<ITest>
{
public ITest GetInstance<ITest>
{
return new (ITest)OneImplementationOfITest();
}
}
Run Code Online (Sandbox Code Playgroud)
然后定义ServiceLocator,如下所示:
public static class ServiceLocator
{
private static Dictionary<string,object> m_Factories;
public static T GetInstance<T>
{
string type = typeof(T).ToString();
return ((IFactory<T>)Factories[type]).GetInstance();
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,IFactory中的T给出了编译器错误:
"T必须是引用类型才能在通用类型的方法中将其用作参数T ......"
我可以想办法解决这个问题,例如定义IFactory而不是IFactory:
public interface IFactory
{
object GetInstance();
}
Run Code Online (Sandbox Code Playgroud)
但是用户需要自己投射对象:
ITest test = (ITest)ServiceLocator<ITest>.GetInstance();
Run Code Online (Sandbox Code Playgroud)
这是相当尴尬,可能导致错误(例如,没有正确地投射)
更好的是如果有办法写:
ITest test = ServiceLocator.GetInstance("ITest")但还没弄明白该怎么做.
0我想将操作的输出插入到视图中。问题是该操作需要查询字符串中的一些信息。有没有办法在 Action 中包含查询字符串参数?
例子:
@Html.Action("Get","Contacts")
Run Code Online (Sandbox Code Playgroud)
为了获得正确的结果,我需要将 ?pagenum=1 传递给操作。
@Html.Action("Get?pagenum=1","Contacts") unfortunately doesn't work
Run Code Online (Sandbox Code Playgroud)