Search code examples
c#usingactivator

How can I use Activator.CreateInstance to instantiate a generic type as part of a using block?


What I'd like to achieve is to convert the following method to something more generic:

    private Task<TestResult> SpecificServiceWarmUp(string serviceEndPoint)
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {

            using (var service = new MySpecificClient(serviceEndPoint))
            {
                // do some stuff with specific client
            }
        });
    }

A more generic version would look like:

    private Task<TestResult> GenericServiceWarmUp<TService>(string serviceEndPoint)
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {

            using (/* instance of TService */)
            {
                // do some stuff with generic client
            }
        });
    }

What I don't know is how to tell the using block to use Activator to create the instance of the generic type. Is this possible? If so, how can I do this?


Solution

  • You can add a constraint on your generic type parameter like that:

    private Task<TestResult> GenericServiceWarmUp<TService>()
    where TService : IDisposable
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {
            using (var service = 
                (TService)Activator.CreateInstance(typeof(TService), serviceEndPoint))
            {
                // do some stuff with generic client
            }
        });
    }
    

    Otherwise if your service has no constructor parameter you don't need to use Activator.CreateInstance, there is a new() constraint:

    private Task<TestResult> GenericServiceWarmUp<TService>(string serviceEndPoint)
    where TService : IDisposable, new()
    {
        return Task<TestResult>.Factory.StartNew(() =>
        {
    
            using (var service = new TService())
            {
                // do some stuff with generic client
            }
        });
    }