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: 285
        
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,
TTypeshould always implementTContract(Enforced using a generic constraint)TContractmust be an interface (Can't find a way to enforce it)TTypeshouldn't have public constructor, just an internal one, is there any way to Enforce that usingControllerBase?TTypemust 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