Improve this generic abstract class

Posted by Keivan on Stack Overflow See other posts from Stack Overflow or by Keivan
Published on 2010-05-14T17:38:09Z Indexed on 2010/05/15 22:30 UTC
Read the original article Hit count: 210

I have the following abstract class design, I was wondering if anyone can suggest any improvements in terms of stronger enforcement of our requirements or simplifying implementing of the ControllerBase.

//Dependency Provider base
public abstract class ControllerBase<TContract, TType> where TType : TContract, class
{
    public static TContract Instance 
    {
        get { 
    return ComponentFactory.GetComponent<TContract, TType>(); 
            }
    }

 public TContract GetComponent<TContract, TType>() where TType : TContract, class
 {   
        component = (TType)Activator.CreateInstance(typeof(TType), true);
        RegisterComponentInstance<TContract>(component);
 }
}

//Contract
public interface IController
{
 void DoThing();
}

//Actual Class Logic
public class Controller: ControllerBase<IController,Controller>
{
 public void DoThing();

    //internal constructor
    internal Controller(){}

}


//Usage
public static void Main()
{
 Controller.Instance.DoThing();
}

The following facts should always be true,

  • TType should always implement TContract (Enforced using a generic constraint)

  • TContract must be an interface (Can't find a way to enforce it)

  • TType shouldn't have public constructor, just an internal one, is there any way to Enforce that using ControllerBase?

  • TType must be an concrete class (Didn't include New() as a generic constrain since the constructors should be marked as Internal)

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics