依赖注入DI(IOC 控制器反转)之Ninject应用
1.安装并引用Ninject install-package Ninject -verion 3.0.1.10 using Ninject
2.建立接口以及与之对应的实现类
3.通过实例化Standardkernel() 建立IKernel 接口对象kernel
4.通过kernel绑定接口与类 kernel.Bind<IMyService>().To<MyService>()
5.获取目标接口对象 IMyService myservice=kernel.Get<IMyService>();
6.使用目标对象 myservice.info()
这样就可以随时更换实现类,只要修改绑定即可,当然也可以通过配置文件加上反射Type.GetType("typename") 来通过配置获取对象类型
实例效果:
源码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject;
using ConsoleApp6.Model;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kernel依赖注入步骤:\n1.通过new StandardKernel()实例化内核对象\n 2.通过内核对象绑定接口与实例类\n 3.通过内核对象的Get方法获取目标接口对象");
IKernel kernel = new StandardKernel();
kernel.Bind<IMyService>().To<MyService1>();
IMyService myService = kernel.Get<MyService1>();
myService.Info("wang");
kernel.Bind<IMyService>().To<MyService2>();
myService = kernel.Get<MyService2>();
myService.Info("zhang");
Console.ReadLine();
}
}
接口 与 类
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp6.Model
{
public interface IMyService
{
void Info(string msg);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApp6.Model;
namespace ConsoleApp6.Model
{
public class MyService1 : IMyService
{
public void Info(string msg)
{
Console.WriteLine("Hello " + msg + " I'am Service1");
}
}
public class MyService2 : IMyService
{
public void Info(string msg)
{
Console.WriteLine("Hello " + msg + " I'am Service2");
}
}
}