简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM