?
Solved

Using Simpleject with Class Library

Posted on 2016-11-02
11
Medium Priority
?
70 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses
Course of the Month15 days, 2 hours left to enroll

770 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