Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Started with LightInject

I love the benchmarks on LightInject; they are insane! Way to go, you should write a book on .Net performance, I'm serious.

I see the documentation.

I got the dll installed. Followed that step ok.

Then the next step of the documentation presumes I have a container object.

container.Register<IFoo, Foo>();
var instance = container.GetInstance<IFoo>();
Assert.IsInstanceOfType(instance, typeof(Foo));

Whoops! I may not be the sharpest crayola in the box, granted, but what do I do now? What class and methods should I create to "set it up" so I can follow the rest of the examples? (I guess I better set it up so that it works in the whole project)

As an aside: Would it be wrong to add those steps in the doc at that point, if not explicitly, then by reference to other "man pages"? Maybe there are various ways of getting a container; I don't know enough to know which one I need. At this point in the documentation I was just looking for the "this will work in 90% of the situations" example, and links to more specialized cases.

Thanks!

like image 341
toddmo Avatar asked Mar 12 '15 19:03

toddmo


Video Answer


1 Answers

You should be good to go. IFoo is your interface and Foo is the concrete implementation. You should be able to do whatever you want. The tutorial is just showing you what's needed for the DI. For example, create method DoStuff in your IFoo, implement it in Foo and then call it: 'instance.DoStuff();'

Something like:

using LightInject;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new ServiceContainer();
            container.Register<IFoo, Foo>();
            container.Register<IBar, Bar>();
            var foo = container.GetInstance<IFoo>();
            foo.DoFooStuff();
        }
    }

    public interface IFoo
    {
        void DoFooStuff();
    }

    public class Foo : IFoo
    {
        // this property is automatically populated!
        public IBar MyBar { get; set; }

        public void DoFooStuff()
        {
            MyBar.DoBarStuff();
            Console.WriteLine("Foo is doing stuff.");
        }
    }

    public interface IBar
    {
        void DoBarStuff();
    }

    public class Bar : IBar
    {
        public void DoBarStuff()
        {
            Console.WriteLine("Bar is doing stuff.");
        }
    }
}
like image 66
Paul Sasik Avatar answered Sep 21 '22 15:09

Paul Sasik