Using Simpleject with Class Library

1

I'm starting to use simpleject for dependency injection.

I created the BootStrapper class to register the containers:

public class  BootStrapper
{
    public static void RegisterServices(Container container)
    {

        container.Register<IRepository, Repository>(Lifestyle.Singleton);
        container.Verify();
    }

}

I created the SimpleInjectorInitializer class to start the simpleinject settings:

 public class SimpleInjectorInitializer
{
    public static void Initialize()
    {
        var container = new Container();          
        InitializeContainer(container);
        container.Verify();

    }

    private static void InitializeContainer(Container container)
    {
        BootStrapper.RegisterServices(container);
    }
}

At the start of the class I call:

 SimpleInjectorInitializer.Initialize();

My variable is declared as

 private readonly IRepository _Repository;

When I run the command:

Console.WriteLine("Teste" + _repository.SelecionarRegistroPorCommando("123"));

The compiler reports that it does not have an instance of the object.

 class Program
{
    static void Main(string[] args)
    {
        var test = new TesteIoC();
    }


}

public class TesteIoC
{
    private readonly IRepository _Repository;
    public TesteIoC()
    {
        SimpleInjectorInitializer.Initialize();
        Console.WriteLine("Teste" + _repository.SelecionarRegistroPorCommando("123"));
    }
}
    
asked by anonymous 02.11.2016 / 08:54

1 answer

2

In console application , it is different, you need to use the commands within classe Main to work. If for web you can work with dependency injection, but in your specific case ( Console Application ) you have nothing in < strong> documentation that says that this works, at most what's in the code below:

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            var container = new Container();
            container.Register<IRepository,Repository>(Lifestyle.Singleton);
            container.Verify();

            //instânciado pelo container manualmente
            IRepository rep = container.GetInstance<IRepository>();            

            System.Console.WriteLine("Pression <Enter>");
        }
    }
}

Do the tests in ASPNET Web that will work just like the documentation , then you get the full benefit of that package.

    
02.11.2016 / 19:54