seesharper / LightInject.Annotation

LightInject.Annotation supports annotation of properties and constructor parameters through an extension LightInject.
3 stars 1 forks source link

Am I using it wrong ? #6

Closed philippe-lavoie closed 7 years ago

philippe-lavoie commented 7 years ago

The following doesn't work, I think I'm following the examples, so I'm a bit baffled. I tried with .net core and .net framework. I think the first was with lightinject5, the other lightinject 4

using LightInject;
using System;

namespace LightInjectAnnBug
{
    public interface SomeInterface
    {
    }

    public class SomeImplementation : SomeInterface
    {
    }

    public class AnotherImplementation : SomeInterface
    {

    }

    public class BaseClass
    {
        [Inject("A")]
        public SomeInterface SomeA { get; set; }
        [Inject("B")]
        public SomeInterface SomeB { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var container = new LightInject.ServiceContainer();
            container.Register<SomeInterface, SomeImplementation>("A");
            container.Register<SomeInterface, AnotherImplementation>("B");
            container.Register<BaseClass>();

            var instance = container.GetInstance<BaseClass>();

            if (instance.SomeA == null)
            {
                throw new Exception("Some A should be set by lightinject.annotation");
            }

            if (instance.SomeB == null)
            {
                throw new Exception("Some B should be set by lightinject.annotation");
            }
        }
    }
}
philippe-lavoie commented 7 years ago

Turns out I was using it wrong, not sure why I didn't clue in that I needed

container.EnableAnnotatedPropertyInjection();