DryIoc and UseInstance leads to "Expecting the instance to be stored in singleton scope" exception - dryioc

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.

Related

Is this code bad design, what's the alternative

I recently implemented some code similar to below and submitted a pull request to get it added to our shared repository. The request was rejected and I was told this pattern was bad. Instead I should be putting my dependencies closer to the creation of my objects. If the parent object creates a child object then a Func childFactory should be passed in rather than a more generic object since that could be misused, increases coupling and becomes much harder to test.
public interface ILogResolverService
{
ILogger<T> Resolve<T>();
}
public class LogResolverService : ILogResolverService
{
private readonly IContainer _container;
public LogResolverService(IContainer container)
{
_container = container;
}
public ILogger<T> Resolve<T>()
{
return _container.Resolve<ILogger<T>>();
}
}
The idea of the code is to pass an object that can create an ILogger so that you can log with the correct class name. If you create a child view model for example you would let it create it's own ILogger etc
Since this issue has polarized opinions amoungst my colleagues I wanted to get an opinion from the community.
Added After Comments
I should have added that I don't see this as a ServiceLocator pattern because it is a strongly typed interface passed into the constructor of a parent. So you know all your dependencies up front. The worse that can happen is a new method is added to the interface ILogResolverService. Unless I'm missing something.
For what I can tell with the design you've outlined above, the main issue here is with your service being somewhat container aware.
Even if the return values you're proving are strongly typed and unambiguous the tricky part is somewhere else. The domain knowledge is too broad and overlap the container job.
It's always a good practice to explicitly provide the dependency your builder is using via an Add method.
public AddLoggerService[...]
Depending of your context you can ask the container to decorate/compile such service by adding all the needed dependency runtime.
Hope i have shed some light on the matter,
Regards.

How to use Moq to simulate exceptions thrown by the StackExchange.Redis library?

I'm working on a project where I would like to use the StackExchange.Redis library to connect to a Redis database. In addition, I'd like to use Moq for the mocking library in our unit tests, but I'm running into a roadblock that I need some help to resolve.
My specific issue, is that I have a command/response architecture and I'm trying to test a cache "wrapper" that checks if a command can be satisfied by the cache before doing the actual work to return the response. An important consideration is that cache failures should never stop a request from being handled, so I want to to mock out certain failures for the StackExchange.Redis IDatabase interface. However, I can't seem to figure out how to throw a RedisException from my mocked object. For example, I'd like to just use the following code, but it doesn't compile because there's no public constructor for the exceptions thrown by this library.
Mock<IDatabase> _mockCache = new Mock<IDatabase>();
// Simulate a connection exception to validate how the cache layer handles it
// THIS DOESN'T COMPILE THOUGH
//
_mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws<RedisException>();
Is there a better way to mock up failures within the StackExchange.Redis library? I feel like I'm missing something obvious either with Moq or with how to test against this library.
You can always use FormatterServices.GetUninitializedObject to create an instance of a class without running any constructor:
Creates a new instance of the specified object type.
Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.
So your setup could look like this:
var e = (RedisException)FormatterServices.GetUninitializedObject(typeof(RedisException));
Mock<IDatabase> _mockCache = new Mock<IDatabase>();
_mockCache.Setup(cache => cache.StringGetAsync("a", CommandFlags.None)).Throws(e);
It's a little hackish; since no constructors are run, you should not rely on a valid state of the RedisException instance.

What do I name this class whose sole purpose is to report failure?

In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class:
class IConstructor {
public:
virtual void Update() = 0;
virtual Status GetStatus() = 0;
virtual int GetLastError() = 0;
};
There's an issue with the design of the current system - the functions that create the IConstructor-derived classes are often doing additional work which can also fail. At that point, instead of getting a constructor which can be queried for an error, a NULL pointer is returned.
Restructuring the code to avoid this is possible, but time-consuming. In the meantime, I decided to create a constructor class which we create and return in case of error, instead of a NULL pointer:
class FailedConstructor : public IConstructor
public:
virtual void Update() {}
virtual Status GetStatus() { return STATUS_ERROR; }
virtual int GetLastError() { return m_errorCode; }
private: int m_errorCode;
};
All of the above this the setup for a mundane question: what do I name the FailedConstructor class? In our current system, FailedConstructor would indicate "a class which constructs an instance of Failed", not "a class which represents a failed attempt to construct another class".
I feel like it should be named for one of the design patterns, like Proxy or Adapter, but I'm not sure which.
EDIT: I should make it clear that I'm looking for an answer that adheres to, ideally, one of the GoF design patterns, or some other well-established naming convention for things of this nature.
To answer your literal question, I'd probably go with ConstructorFailure, as it describes the event of failing.
However, I'd probably go one step further and make it an Exception, in which case ConstructorException doesn't sound too shabby. Any reason you want to return this instead of throwing it?
I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern
Throw an exception. That is If I understand your description correctly and the creation of the IConstructor object is not done asynchronously.
Though if you don't have exceptions available to you I would probably call it ConstructorCreationError. Yes it does convey a failure mode but, more accurately, it is communicating the specific error that occurred. Also, having constructor as the last word, to me, seems to give the wrong meaning, but you could put "constructor" at the end as well.
You could also replace the verb "Creation" with something like SpawnConstructorError, ConstructorGenerationError and or if you're a fan of Dr. Chevalier maybe ErroneousConstructor.
I'd go for DummyConstructor because its only purpose is to simulate a valid Constructor instance, but no real functionality is implemented by it.
FailureResponseConstructor?
You're not creating a failure, you're creating the response to the failure. Thus, I would think any synonym to 'response' or 'respond' would work.
If you willing to spend effort checking returned pointer against the "FailureConstructor", I don't see reason why couldn't you check it against NULL ?
Unless your system is designed to mask component failure from each other, it just doesn't make sense to assume every associated parts are working well.
I'm going to go with something based on Niall C.'s comment -- FailedConstructorProxy. The Proxy pattern seems to fit best with what this class is; though rather than it relaying method calls to an object, it's standing in and generating what we wanted the actual constructor to return.
(If someone has a more correct answer, post it and I'll mark that one as accepted. I'm still not 100% convinced this is the right name!)
Why not create a Failed class to represent a class that failed construction and go with FailedConstructor? This way the naming is consistent.
I would suggest calling this class FailedObjectConstructionHandler which describes what the class does.

How to create a global parameters object

Here's a common, simple task: Read configuration settings from a configuration file, save the settings (e.g. as a hash) in an object, access this object from various objects that need to access the configuration parameters.
I found this implementation for the ConfigFile class implementation and it works. My question is: what is the best way to make an instance of this class available from my other classes and be thread safe, avoid static initialization order fiasco, etc.
My current approach is to construct it in main() using
// Read face detection related parameter values from the configuration file.
string configFileName = "detection_parameters.txt";
try {
parameters = ConfigFile( configFileName );
}
catch(ConfigFile::file_not_found) {
cerr << "configuration file not found: " << configFileName << endl;
exit(-1);
}
and then make parameters a global variable. But I also read that singletons should be used instead of global variables. How can the singleton be instantiated with the file name?
This must be such a common task that I think there must be a generally accepted good way of doing it? I would appreciate if someone can point me to it.
Thanks,
C
If you're going to roll-your-own, I would recommend using the Singleton design pattern for your configuration class.
Have the class itself store a static pointer of its own type, and the constructor be private so one would be forced to use the static getter to get the one instance of the class.
so a mock-up (that may not compile, an is missing the fun Config functionality, but should illustrate the point)
class Config
{
public:
static Config * getConfig();
static void setConfigFileName(string filename);
private:
Config();
static string m_filename;
static Config * m_configInstance;
};
In case I'm not being clear, the getConfig() would look at m_configInstance. If it isn't a valid one, then it would create one (has access to the private constructor) and store it in m_configInstance so every subsequent call would access the same one.
So your main() would use setConfigFileName(), then any class would just have to call Config::getConfig() and then call the operations on it. A lot cleaner than a standard global variable.
Blast - in the time I spent writing this, other people have suggested the singleton design pattern too. Ah well - hope the additional explanation helps.
Have you looked at Boost's Program Options library?
What I have done for my configuration class is to create a singleton static class with a hashtable cache. My configuration file is designed to be read and written to for changing application settings.
Whenever a call is made to pull a setting, I perform a lookup on the hashtable, if it's not there, then I read the setting from the file, lock the hashtable, and put it into the hashtable. The hashtable very fast for lookups.
By mentioning the "static initialization order fiasco", I assume you need to have configuration items available to initialize some static objects. A singleton ConfigFile class will work, but you have to change the way you obtain the filename as the information is needed before main() is started. You'll need another singleton to provide the filename, or build the filename into the configuration class itself.
I agree with Chris, use a singleton. The nice thing about the singleton pattern is that it only initializes/gathers the data you need the first time you try to access it, from there on out it is available to everybody that is interested. If you are going to allow the configuration to change you will want to lock the writer.
I have used a technique similar to the singleton design pattern to configure global resources like this.
class Config
{
public:
Config(const string & filename) {
if (m_configInstance) {
throw AlreadyInitException;
}
// do main init
m_configInstance = this;
}
~Config() {
m_configInstance = 0;
}
static Config * getConfig() {
if (!m_configInstance) {
throw NoConfigException;
}
return m_configInstance;
}
private:
static Config * m_configInstance;
};
Config * Config * m_configInstance = 0;
The constructor tests that m_configInstance is not set, if it is it throws an exception. Then it finishes contruction and registers itself by setting m_configInstance to this.
The getConfig method returns the instance or throws and exception if it is not set.
The destructor sets the m_configInstance to 0 again.
To use the class construct it once in the start of main(). Then access it when required by the getConfig() method.
Now the lifetime of the Config object is cleanly controlled, unlike a singleton. And this has an added benefit for unit tests, each test or suite of tests can create there own Config object and they are all nicely cleaned up between tests.

Unit Testing: TypeMocking a singleton

I'm using TypeMock Isolater to mock up some objects for some unit tests - attempting to use the AAA api (so the Isolate calls).
I have a straightforward singleton class where you call a static GetInstance(), which then returns an instance of the class. I thought it would be a simple matter of mocking that up, but I'm running into a very frustrating problem ! I can't seem to make GetInstance() return my mocked object correctly with my expected calls set.
I've tried:
using MST projects (using the Accessor classes) to assign a mocked object directly to the instance variable (faking the object using Memers.MustSpecifyReturnValues, and Isolate.WhenCalled using WithExactArguments to set expectations), but for some reason the mocked object always returns null (and no exceptions).
Mocking Singleton.GetInstance() to return the mocked object. This returns a mocked object which needs WhenCalled set, but now the Isolate.WhenCalled calls I make seem to do nothing on the fake object - so all calls throw an unexpected call exception.
I've also tried mocking the actual method call (eg Singleton.GetInstance().Test()), which will work for the call to that method, but all other calls to other methods on the singleton return null rather then throw an exception as I want it to (because this seems to automatically mock up all the objects without Members.MustSpecifyReturnValues).
All I want is to mock a singleton, and any calls I don't explicitly tell it to expect to throw an exception on. I thought it would be simple, but apparently not ! Sad
Has anyone any idea what I'm doing wrong?
Thanks
James
I think the simple solution will be to create a fake instance of the singleton class and use SwapNextInstace before the actual class constructor is called:
[TestMethod]
public void SetBhaciorOnSingleton()
{
var fake = Isolate.Fake.Instance<SingletonClass>();
Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);
// Set additional behavior on singleton class
Isolate.Swap.NextInstance<SingletonClass>().With(fake);
// This is where the class constructor is being called
var result = SingletonClass.GetInstace().SomeFunction();
Assert.AreEqual(10, result );
}
This solution should work with most scenarios unless the singleton class is created before the test.
If you need to set behavior after the class was created just use WhenCalled:
[TestMethod]
public void SetBhaciorOnSingleton()
{
var fake = Isolate.Fake.Instance<SingletonClass>();
Isolate.WhenCalled(() => fake.SomeFunction()).WillReturn(10);
Isolate.WhenCalled(() => SingletonClass.GetInstace()).WillReturn(fake);
var result = SingletonClass.GetInstace().SomeFunction();
Assert.AreEqual(10, result );
}
Disclaimer I work at Typemock.
You don't need to mock Singleton.GetInstance<>(). Using Isolate.Fake.AllInstances<>() instead of Isolate.Fake.Instance<>() you can mock the singleton. Then by setting the behavior on fake singleton behavior applied to all instances.
Take a look on the example:
public class Singleton
{
private Singleton() { }
static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
public int ReturnZero()
{
return 0;
}
}
[TestMethod]
public void FakeSingleton()
{
// Here we are setting the same behavior on all instances.
// The behavior we set on fake will apply to past instance as well
var fakeSingleton = Isolate.Fake.AllInstances<Singleton>();
Isolate.WhenCalled(() => fakeSingleton.ReturnZero()).WillReturn(10);
// Assert that the behavior works.
Assert.AreEqual(10, Singleton.Instance.ReturnZero());
}
Thanks.
I didn't try NextInstance before because it doesn't work on interfaces which I didn't really want to change.
But, I've tried it and it does work - although I was assuming the order of setting WhenCalled(s) doesn't really matter, but it definately does. If I do the WhenCalled after the Swap for instance, it doesn't work. It needs to go before the Swap. (Doesn't really make sense to me to be honest - it should be the same object).
However, the last example (one of the ways I had tried), doesn't work for me. I fake, set expecation on fake, and then set expectation on Singleton to return faked instance - but now it returns the concrete instance !
Could it have something to do with the way the constructors are called? I remember seeing something about that...
Alternatively I could use the Swap, but, I wanted to be able to setup all this stuff in a TestSetup, and make minor modifications to the expectations in the actual test, but that doesn't look possible. ?
The best solution is to not use singletons (or any other static mutable data). Just create one instance and use dependency injection to pass it to all objects who need it.
http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
http://www.youtube.com/watch?v=-FRm3VPhseI