一、Unity
1. 创建一个IService服务接口,并创建一个服务实现了Service
public interface IService
{
void DoSomething();
}
public class Service : IService
{
public void DoSomething()
{
Console.WriteLine("Service is doing something.");
}
}
2. 创建一个控制器类,且依赖于IService
public class Controller
{
private readonly IService _service;
public Controller(IService service)
{
_service = service;
}
public void DoWork()
{
_service.DoSomething();
}
}
3.使用 Unity 容器进行依赖注入,将 IService 实例注入到 Controller 中
using System;
using Unity;
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
// 注册服务接口和实现类
container.RegisterType<IService, Service>();
// 解析控制器实例
var controller = container.Resolve<Controller>();
// 使用控制器
controller.DoWork();
Console.ReadLine();
}
}
二、AutoFac
1. 安装AutoFac类库,在NuGet搜索下载安装即可
2. 创建一个IService服务接口,并创建一个服务实现了Service
public interface IMyService
{
void DoSomething();
}
public class MyServiceImpl : IMyService
{
public void DoSomething()
{
Console.WriteLine("Doing something...");
}
}
3. 创建Autofac容器,并将IMyService接口和MyServiceImpl实现类进行注册
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyServiceImpl>().As<IMyService>();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
service.DoSomething();
}
}
}
三、Ninject
1. 安装Ninject类库,在NuGet搜索下载安装即可
2. 创建一个IService服务接口,并创建一个服务实现了Service
public interface IMyService
{
void DoSomething();
}
public class MyServiceImpl : IMyService
{
public void DoSomething()
{
Console.WriteLine("Doing something!");
}
}
3. 创建一个Ninject内核并注册我们的服务
using Ninject;
class Program
{
static void Main(string[] args)
{
// create a new Ninject kernel
var kernel = new StandardKernel();
// register our service
kernel.Bind<IMyService>().To<MyServiceImpl>();
// get an instance of our service
var service = kernel.Get<IMyService>();
// use our service
service.DoSomething();
Console.ReadLine();
}
}