Resolution Failed when calling Constructor

Jun 30, 2014 at 6:30 AM
Edited Jun 30, 2014 at 6:31 AM
Currently, I'm having problem in using injected properties in the constructor, here is the code for the unit test:
[TestClass]
    public class CryptographyUnitTest
    {
        private IUnityContainer container;

        [TestInitialize]
        public void InitializeTest() 
        {
            container = new UnityContainer()
                .RegisterType<ILogger, Logger>()
                .RegisterInstance(new Logger());
        }

        [TestMethod]
        public void AesEncryptDecryptTextTest()
        {
            // Arrange
            Byte[] plainBytes = Encoding.UTF8.GetBytes("This is a plain text for Cryptography Unit Test.");
            Byte[] cipherBytes = null;
            Byte[] resultBytes = null;
            container.RegisterType<ICryptography, Cryptography>(new InjectionConstructor(
                new InjectionParameter(typeof(CryptographyAlgorithm), CryptographyAlgorithm.Aes)));
            ICryptography cryptography = container.Resolve<Cryptography>();

            // Act
            cipherBytes = cryptography.Encrypt(plainBytes);
            resultBytes = cryptography.Decrypt(cipherBytes);

            // Assert
            Assert.AreEqual(Encoding.UTF8.GetString(plainBytes), Encoding.UTF8.GetString(resultBytes));
        }
    }
and here is the class:
[Dependency]
        public ILogger Logger { get; set; }

        public Cryptography(CryptographyAlgorithm cryptographyAlgorithm)
        {
            this.cryptographyAlgorithm = cryptographyAlgorithm;
            Logger.Write("Hello World", LoggerLevel.Informational);
        }
Here is the error:
Result Message: 
Test method GPdIPalmerahTimur.Products.Components.Tests.Security.CryptographyUnitTest.AesEncryptDecryptTextTest threw exception: 
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "GPdIPalmerahTimur.Products.Components.Security.Cryptography", name = "(none)".
Exception occurred while: Calling constructor GPdIPalmerahTimur.Products.Components.Security.Cryptography(GPdIPalmerahTimur.Products.Components.Security.CryptographyAlgorithm cryptographyAlgorithm).
Exception is: NullReferenceException - Object reference not set to an instance of an object.
-----------------------------------------------
At the time of the exception, the container was:

  Resolving GPdIPalmerahTimur.Products.Components.Security.Cryptography,(none)
  Calling constructor GPdIPalmerahTimur.Products.Components.Security.Cryptography(GPdIPalmerahTimur.Products.Components.Security.CryptographyAlgorithm cryptographyAlgorithm)
 ---> System.NullReferenceException: Object reference not set to an instance of an object.
How to fix this problem?
Jun 30, 2014 at 11:49 AM
you can't use the property in the constructor as it will be set AFTER the object is constructed.
Marked as answer by jazzyhacker on 6/30/2014 at 7:42 AM
Jun 30, 2014 at 12:06 PM
powerdude wrote:
you can't use the property in the constructor as it will be set AFTER the object is constructed.
So what should I do, if I want to inject the Logger instance into the container and use it in the constructor, without passing it as constructor parameter?
Jun 30, 2014 at 1:17 PM
to the best of my knowledge, what you ask is not possible. Ask yourself, how can you use a dependency in the method that creates the object if you don't pass the dependency to it because the object doesn't exist yet?

Either pass it in the constructor, or don't use it in the constructor.
Jun 30, 2014 at 1:20 PM
powerdude wrote:
to the best of my knowledge, what you ask is not possible. Ask yourself, how can you use a dependency in the method that creates the object if you don't pass the dependency to it because the object doesn't exist yet?

Either pass it in the constructor, or don't use it in the constructor.
What is the best practice for this? Is it passing the instance through the constructor or never use the object in the constructor. This object (Logger) is a dependency because it is used in every class.
Jun 30, 2014 at 2:09 PM
From what I've seen most people (but not all) recommend using constructor injection to inject dependencies. This has the benefit of constructing objects that are always in the proper state (and using the dependencies in the constructor if you need to). Another benefit is that there is no need to expose internal dependencies via properties for no reason other than dependency. Do users of the Cryptography class need access to the Logger property? And should they be allowed to set the Logger property to some other value?

You can do a search and read some of the arguments for yourself. I agree with Martin Fowler's approach](http://martinfowler.com/bliki/ConstructorInitialization.html) of preferring constructor injection but using other methods where appropriate.

Another best practice is to not have your classes depend on the container (unless absolutely required). So, don't use the DependencyAttribute or inject the container into your class.


~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Marked as answer by jazzyhacker on 6/30/2014 at 7:42 AM