Solved

Using Simpleject with Class Library

Posted on 2016-11-02
11
42 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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
 
LVL 75

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 75

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 75

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Question! 4 39
C# Gridview 1 48
Code works but breaks when I add one section 4 20
Where does legacy ASP.NET initialize language? 2 26
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

830 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