Solved

Using Simpleject with Class Library

Posted on 2016-11-02
11
25 Views
Last Modified: 2016-11-02
I'm beginning to use simplejec to Injection of dependency.

I've create the class BootStrapper to refister of the containers:

public class  BootStrapper
{
    public static void RegisterServices(Container container)
    {
        container.Register<IRepository, Repository>(Lifestyle.Singleton);
        container.Verify();
    }

}

Open in new window


I've created the class SimpleInjectorInitializer to initializer the simpleinject:

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

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

Open in new window


In the constructor of class :

 SimpleInjectorInitializer.Initialize();

Open in new window


I have this variable

private readonly IRepository _Repository;
Console.WriteLine("Test" + _repository.GetById("123"));

Open in new window


The compiler show the message:

System.NullReferenceException was unhandled
  HResult=-2147467261
  Message=Object reference not set to an instance of an object.
0
Comment
Question by:berechit
  • 4
  • 4
  • 3
11 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41869754
Your code doesn't show everything, some variables are used with no indication of what they are or when and how created.

Please show more complete code.  
It would be of great help if you could actually show which line of code fails.  The code posted may not even be the problem code.  At present you are assuming it fails and not some other piece of code you have.
0
 

Author Comment

by:berechit
ID: 41869778
 public  class ClassTest
    {
        private readonly IRepository _repository;
        public ClassTest()
       {
            SimpleInjectorInitializer.Initialize();
            Console.WriteLine("Test=" + _repository.GetById("123"));
        }
    }

Open in new window

If I create a instance of Repository It works
[code] public  class ClassTest
    {     
        public ClassTest()
       {
            var _repository = new Repository();
            Console.WriteLine("Test=" + _repository.GetById("123"));
        }
    }

Open in new window

0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41869878
public  class ClassTest
    {
        private readonly IRepository _repository;   //_repository is null at this point
        public ClassTest()
       {
            SimpleInjectorInitializer.Initialize();
            Console.WriteLine("Test=" + _repository.GetById("123"));  //_repository is still null at this point - hence your error
        }
    }
0
 

Author Comment

by:berechit
ID: 41869885
public  class ClassTest
    {
        private readonly IRepository _repository;   //_repository is null at this point
        public ClassTest()
       {
            SimpleInjectorInitializer.Initialize();
            Console.WriteLine("Test=" + _repository.GetById("123"));  // How to get a instance here?
        }
    }

 I want to use simpleinject to create a IoC
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41869948
public  class ClassTest
    {
        private readonly IRepository _repository;   //_repository is null at this point
        public ClassTest()
       {
            SimpleInjectorInitializer.Initialize();
_repository = new Repository();   //Create an instance here
            Console.WriteLine("Test=" + _repository.GetById("123"));  
        }
    }

>>I want to use simpleinject to create a IoC
If you want that then it must have a mechanism to return a Repository object.

example code:
 public class SimpleInjectorInitializer
{
  public Repository GetRepository()  { return new Repository(); }
....
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 41870103
What kind of project is this? Console? WinForms? WPF? ASP.NET? Depending on the project type, you may need to maintain a reference to the container because...

You have to resolve your instance from the container:

 public  class ClassTest
    {
        private readonly IRepository _repository;
        public ClassTest()
       {
            SimpleInjectorInitializer.Initialize();
            _respository = container.Resolve<IRepository>();   // THIS
            Console.WriteLine("Test=" + _repository.GetById("123"));
        }
    }

Open in new window


If this is an ASP.NET project, then this resolution can happen automagically, but you have to set the dependency resolver for the application in order for this to happen.
0
 

Author Comment

by:berechit
ID: 41870194
It' a solution with many projects, in this case this is a Class Library. I'm using a Console application to access the Class Library.

In future I will use this Class Library in a Windows Service;
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 41870216
TMK, there are no built-in DI bits for Console applications. So you will need to maintain the reference to your container in a scope that is visible to any code that needs to resolve instances. Once you do that, simply use the resolution logic I demonstrate above.
0
 

Author Comment

by:berechit
ID: 41870227
How I do to maintain the reference to my container to any code?

Can you give more details please?
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 41870285
Widen the scope of the container variable. As an example:

public class Program
{
    public static void Main(string[] args)
    {
        Container container = new Container();
        SimpleInjectorInitializer.Initialize(container);
        
        ClassTest instance = new ClassTest(_container);
    }
}

public class  BootStrapper
{
    public static void RegisterServices(Container container)
    {
        container.Register<IRepository, Repository>(Lifestyle.Singleton);
        container.Verify();
    }
}

public class SimpleInjectorInitializer
{
    public static void Initialize(Container container)
    {
        InitializeContainer(container);
        container.Verify();
    }

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

public  class ClassTest
{
    private readonly IRepository _repository;

    public ClassTest(Container container)
    {
        SimpleInjectorInitializer.Initialize();
        _respository = container.Resolve<IRepository>();
        Console.WriteLine("Test=" + _repository.GetById("123"));
    }
}

Open in new window


You can pass the container that you maintain within Program to your ClassTest so that it can resolve instances. You don't *have* to do it this way--you could resolve the instances in Program and pass them to your ClassTest instead, which, quite honestly, would be more in line with DI. The main point of this example is that you have to keep a reference to the container where you can access it from code outside of the initial registrations.
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41871611
I hope you do now understand what your original error was caused by and how it was solved.
1

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction                                                 Was the var keyword really only brought out to shorten your syntax? Or have the VB language guys got their way in C#? What type of variable is it? All will be revealed.   Also called…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now