?
Solved

Using Simpleject with Class Library

Posted on 2016-11-02
11
Medium Priority
?
82 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 45

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 45

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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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 45

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 45

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

Independent Software Vendors: 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!

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

850 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