I'm using ASP.NET Core, and its builtin DI container. I'm using a third-party library (NLog) which I can't change.
My Foo
class has a dependency (by constructor injection).
public class Foo {
private readonly IMyContext _context;
public Foo(IMyContext context) { _context = context; }
// etc.
}
However the library caches the Foo
instance for the duration of the app (that's outside my control). That means it also caches the dependency. And that dependency must not be cached, because it's an EF context which should be scoped.
An alternative is to inject IServiceProvider
, and then to create instances myself.
public class Foo {
private readonly IServiceProvider _sp;
public Foo(IServiceProvider sp) { _sp = sp; }
// etc.
public void bar() {
var context = _sp.GetService<IMyContext>();
// use it
}
}
But as before, that IServiceProvider
instance would be cached for the lifetime of the app.
Is that "safe"? Are there negative repercussions I should know about?