Using C#/Autofac/Moq: I have this class:
public class MyService
{
private readonly IlifetimeScope _scope;
public MyService(ILifetimeScope scope)
{
_scope = scope;
}
public void DoWork()
{
var dbContext = _scope.Resolve<IDataContext>();
}
}
This works at runtime. However, I can't unit test it, since I cannot mock the Resolve() method. It is an extension method.
What's the best way to be able to mock it? The obvious thing would be to inject the IDataContext in the constructor instead of the ILifetimeScope, but for various reasons I cannot.
So, would it work to inject a Func instead?
public class MyService
{
private readonly Func<IDataContext> _dbContext;
public MyService(Func<IDataContext> dbContext)
{
_dbContext = dbContext;
}
public void DoWork()
{
var ctxt = _dbContext();
// do stuff
}
}
As in: I can mock it, but will Autofac figure out how to inject the correct parameter to the ctor? Or is there a better/simpler way to do this?