question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Registration with Async Instance Creator Factory method

See original GitHub issue

Ideally I’d like a Register overload like the following:

Register<TService>(Func<Task<TService>> instanceCreator, Lifestyle lifestyle)

So I could write the following:

container.Register<SqlConnection>(async () =>
{
     var cn = new SqlConnection("myConnString");
     await cn.OpenAsync();
     return cn;
},
Lifestyle.Scoped);

Would this feature make sense for Simple Injector?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:5

github_iconTop GitHub Comments

4reactions
BrettJanercommented, May 4, 2020

Yup that makes sense. Thanks for the explanation. I’d like to inject the same open connection into all my objects per request and have the container worry about managing the lifetime. So would you suggest my SqlConnectionProvider implement IDisposable and look something like below?

public class SqlConnectionProvider : IDisposable
{
    private readonly Lazy<Task<SqlConnection>> _sqlConnection;

    public SqlConnectionProvider(string connectionString)
    {
        _sqlConnection = new Lazy<Task<SqlConnection>>(async () =>
        {
            var cn = new SqlConnection(connectionString);
            await cn.OpenAsync();
            return cn;
        });
    }

    public Task<SqlConnection> GetConnectionAsync() => _sqlConnection.Value;

    public void Dispose()
    {
        if (_sqlConnection.IsValueCreated)
            _sqlConnection.Value.Result.Dispose();
    }
}
0reactions
dotnetjunkiecommented, May 4, 2020

btw, you can also let Simple Injector manage the lifetime of the SqlConnection; this prevents you from having to dispose it. But to be honest, I’m not sure that would make the solution more elegant. But just for completeness, here’s how to do it:

// Simplified SqlConnectionProvider implementation
public class SqlConnectionProvider
{
    private readonly Func<Task<SqlConnection>> _provider;
    public SqlConnectionProvider(Func<Task<SqlConnection>> provider) => _provider = provider;
    public Task<SqlConnection> Connection => _provider();
}
// configuration
var connectionProvider = (InstanceProducer<SqlConnection>)Lifestyle.Scoped.CreateProducer(
    () => new SqlConnection(connectionString), container);

var openConnectionTaskProducer = 
    (InstanceProducer<Lazy<Task<SqlConnection>>>)Lifestyle.Scoped.CreateProducer(() =>
        new Lazy<Task<SqlConnection>>(async () => {
            var cn = connectionProvider.GetInstance();
            await cn.OpenAsync();
            return cn;
        }), container);

container.RegisterSingleton(
    new SqlConnectionProvider(() => openConnectionTaskProducer.GetInstance().Value));
Read more comments on GitHub >

github_iconTop Results From Across the Web

Autofac: Registering an Async Factory method
I'm using Autofac and need to invoke async factory methods which look like this: class AppModel { public static async Task<AppModel> CreateAsync ......
Read more >
injectable - Dart API docs
injectable will automatically register it as an asynchronous factory because the return type is a Future.
Read more >
Async Programming - Patterns for Asynchronous MVVM ...
The first time the AsyncLazy<T> instance is awaited, it will start the asynchronous factory method once on a thread pool thread.
Read more >
How to Write an Async Class Constructor in TypeScript or ...
The init method is one in which you define an async instance method, performing all your async setup as an additional step, after...
Read more >
Async calls in a factory? : r/dartlang
I have a class with a factory as constructor as I need to some initialization logic which from my understanding cannot be done...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found