Lenic.DI Another IOC Container Library Using Delegate

Lenic.DI

Another IOC Container Library Using Delegate.

Characteristic

  • Use delegate generated object.
  • Support the uncertain parameters.
  • Lazy load.

Basic Usage

IContainer container = new Container();

container.Register(null, c => new Person() { Id = 3, Name = "张三" });

var p = container.Resolve<Person>();

Assert.IsInstanceOfType(p, typeof(Person));
Assert.AreEqual(3, p.Id);
Assert.AreEqual("张三", p.Name);

Singleton Lifetime:

IContainer container = new Container();

container.Register(new SingleLifetime(), c => new Person() { Id = 4, Name = "李四" });

var p = container.Resolve<Person>();

Assert.IsInstanceOfType(p, typeof(Person));
Assert.AreSame(p, container.Resolve<Person>());
Assert.AreEqual(4, p.Id);
Assert.AreEqual("李四", p.Name);

And, has other lifetime, Waiting for you to explore.

Use it with iterative method:

IContainer container = new Container();

container.Register(null, c => new Person() { Id = 3, Name = "张三" })
         .RegisterNamed(null, "x", c => new Person() { Id = 4, Name = c.Resolve<Person>().Name });

var p = container.ResolveNamed<Person>("x");

Assert.IsInstanceOfType(p, typeof(Person));
Assert.AreEqual(4, p.Id);
Assert.AreEqual("张三", p.Name);

Auto Register:

IContainer container = new Container();
container.OnResolveError += ContainerExtensions.DefaultRegister();

var p = container.Resolve<Person>();
Assert.IsNotNull(p);

Auto Interface Register:

IContainer container = new Container();
var interfaceRegister = ContainerExtensions.InterfaceRegister();
container.OnResolveError += interfaceRegister;

var im = container.Resolve<IPerson>();
Assert.IsNotNull(im);
Assert.IsInstanceOfType(im, typeof(IPerson));

Auto Generic Register:

IContainer container = new Container();
container.Register(null, c => 16);
container.OnResolveError += ContainerExtensions.GenericRegister(typeof(IList<>), typeof(List<>));

var g = container.Resolve<IList<string>>();
Assert.IsNotNull(g);
Assert.IsInstanceOfType(g, typeof(IList<string>));

And other, will be coming...

Look it on CodePlex, Thank you.

原文地址:https://www.cnblogs.com/lenic/p/3117893.html