开发者

C# return a type without having to know it

开发者 https://www.devze.com 2023-04-05 19:23 出处:网络
I want to create a dictionary of factory objects that can be used for dependency injection. For Example, say that I have a static class called ServiceLocator.An application could use:

I want to create a dictionary of factory objects that can be used for dependency injection.

For Example, say that I have a static class called ServiceLocator. An application could use:

ITest test = ServiceLocator<ITest>.GetInstance()

to get an object implementing the ITest interface.

To implement this I first created an Interface IFactory

public interface IFactory<T>
{
   T GetInstance<T>();
}

Then, for example, a concrete implementation of ITest could look something like this:

public class TestFactory : IFactory<ITest>
{
   public ITest GetInstance<ITest>
   {
     return new (ITest)OneImplementationOfITest();
   }

}

ServiceLocator is then defined like this:

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

Unfortunately, the T in IFactory gives a compiler error:

"T must be reference type in order to use it as a parameter T in the generic type of method..."

I can think of ways around this by, for example defining IFactory instead of IFactory:

public interface IFactory
{
  object GetInstance();
}

but then开发者_如何学Python the user would need to cast the object themselves:

ITest test = (ITest)ServiceLocator<ITest>.GetInstance();

which is rather awkward and could lead to errors (e.g. not casting it correctly)

Even better would be if there were a way to write:

ITest test = ServiceLocator.GetInstance("ITest") but haven't figured out how to do that.


Try this:

public interface IFactory<T>
    where T: class
{
   T GetInstance<T>();
}

This constrains T to be a reference type. By the way, this is one of many avaiable generic type constraints.

0

精彩评论

暂无评论...
验证码 换一张
取 消