3

I can't get my Func to pass across successfully. I inject into the webapi in my startup.cs

services.AddDbContext<MyDataContext>(
    options => options.UseSqlServer(DbGlobals.DevDatabase,
    b => b.MigrationsAssembly("Services.Data.EF")));

services.AddTransient<Func<IMyDataContext>, Func<MyDataContext>>();
services.AddTransient(provider => new Func<IMyDataContext>(() => provider.GetService<IMyDataContext>()));

Then in my controller I have the following;

private ClientService _service;

public ClientController(Func<IMyDataContext> context)
{
    _service = new ClientService(context);
}

and the method in my service is;

private readonly Func<IMyDataContext> _contextFactory;

public ClientService(Func<IMyDataContext> contextFactory)
{
    _contextFactory = contextFactory;
}

public void AddClient(Client model, string userName)
{
    Func<Client> func = delegate
    {
        using (var context = _contextFactory())
        {
             ....
        }
    };

    return this.Execute(func);
}

Now from debugging if I inspect the controller injection I can see the Func is passed in and is at the service level 2. However when it comes to use it in the using statement on context = _contextFactory() it becomes null?

Any ideas what I am doing wrong here please?

3
  • Just for clarification. is context == null or _contextFactory == null ? Commented Mar 15, 2018 at 13:19
  • context = null, i.e. calling _contextFactory() Commented Mar 15, 2018 at 13:35
  • I'm not sure why you use Func<...> for your DataContext but I would assume your function does not generate a context. Commented Mar 15, 2018 at 13:47

1 Answer 1

1

Your definitions are slightly wrong. You need to define that IDataContext and DataContext are related:

services.AddTransient<IDataContext, DataContext>();

Now the DI knows how to create the IDataContext. Now you method just needs to use the service provider to create it when the func is used:

services.AddTransient<Func<IMyDataContext>>(provider => () 
        => provider.GetService<IMyDataContext>());

Now, when your service is created, the DI will inject your Func<>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.