Search code examples
c#.net-core.net-core-2.2

How to set a readonly property in a C# async constructor


I have a service in an ASP .Net Core 2.2 Web API. The constructor is async because it calls an async method. But because the constructor is async, it's complaining about trying to initialize a property.

public class MyService
{
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public async Task MyService(IServiceScopeFactory serviceScopeFactory)
    {
        this._serviceScopeFactory = serviceScopeFactory;
        await DoSomething();
    }
}

It gives me this error:

"A readonly field cannot be assigned to (except in a constructor or a variable initializer)"

Any ideas?


Solution

  • One common example to solve your problem is to create a static method on the class and call the async method from there and well as the constructor.

    public class MyService
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;
    
        public static async Task<MyService> BuildMyService(IServiceScopeFactory serviceScopeFactory)
        {
            await DoSomething();
            return new MyService(serviceScopeFactory);
        }
    
        public MyService(IServiceScopeFactory serviceScopeFactory)
        {
            this._serviceScopeFactory = serviceScopeFactory;
        }
    }