Using Simpleject with Class Library

Asked

Viewed 127 times

1

I am beginning in the use of simpleject for dependency injection.

I created the Bootstrapper class to register 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 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 class startup I call :

 SimpleInjectorInitializer.Initialize();

My variable is stated as

 private readonly IRepository _Repository;

When I will execute the command :

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

Compiler informs that it has no object instance.

 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"));
    }
}
  • You’re testing it where, in a Console Application?

  • Yes I am using a console application to test. This code I posted is from Class Library and in the application console I am instilling the class library.

  • Enter the complete code of your Console Application.

  • Virgilio Novic I edited the question and put the Console Application class

1 answer

2


In console application, is different, you need to use the commands within the classe Main to work. If you are Web you can work with dependency injection, but in your specific case (Console Application) has nothing in the documentation that says it works, at most what is 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 the same as what is in documentation, then you take full advantage of this package.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.