When I try to obtain instance of object, which depends on parameter registered by UseInstance, I get
DryIoc.ContainerException : Expecting the instance to be stored in singleton scope, but unable to find anything here. Likely, you've called UseInstance from the scoped container, but resolving from another container or injecting into a singleton.
Using xUnit:
public interface IFooDao { }
public class FooDao : IFooDao
{
public FooDao(ConnectionStringSettings connString) { }
}
[Fact]
void CompositionRootWontThrowException()
{
var container = new Container();
container.Register<IFooDao, FooDao>(Reuse.Singleton);
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["ConnectionString"];
container.UseInstance(connString);
IFooDao dao = container.Resolve<IFooDao>();
}
So I have this exception message, but I can't find problem and solution with it:
1) I don't have scoped container, because I didn't create it by container.OpenScope()
, right? I have just one container so I can't be resolving from a wrong one. And it's a container
without context (which is default)
as per project wiki
2) So, what does it mean I'm "injecting into a singleton"? I'd like to inject dependency into singleton while creating it - what's wrong with that? Am I doing it anyway?
3) As per docs again, the instance of conn string should be in singleton scope
When you call the UseInstance the instance will be *directly put into Open scope or Singleton scope based on whether the container is scoped (returned from OpenScope call) or not. In addition, the scoped and sington instances may coexist with each other.
I used similar code before, just used DryIoc.MEF extension with ExportManyAttribute
and ImportAttribute
. Usage of UseInstace
was exactly the same as bellow. Everything worked. What am I missing here? Why is this exception thrown?
First I tought this code is so simple it can't fail :)
Problem was in null
being registered.
UseInstance is fine with being given null value, but when you need the actuall dependency, even if the actuall null was resolved, it probably would not be considered to be enough and exception is thrown.
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["ConnectionString"];
returned null, since actuall connection name in config was misstyped.