using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace IOCTest
{
internal class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
//container.RegisterType();
container.RegisterType<Interface5, Class5>();
//Class1 class1 = container.Resolve();
//Class2 class2 = container.Resolve();
//Class3 class3 = container.Resolve();
//Class4 class4 = container.Resolve();
Class5 class5 = container.Resolve<Class5>();
Console.ReadKey();
}
}
}
常规注入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal interface Interface1
{
void Show();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal class Class1 : Interface1
{
public Class1()
{
Console.WriteLine($"{this.GetType().Name}被构造");
}
public void Show()
{
Console.WriteLine($"{this.GetType().Name}--Show");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal interface Interface2
{
void Show();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal class Class2 : Interface2
{
private Class1 _class1 = null;
public Class2(Class1 class1)
{
_class1= class1;
Console.WriteLine($"{this.GetType().Name}被构造");
}
public void Show()
{
Console.WriteLine($"{this.GetType().Name}--Show");
}
}
}
属性注入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal interface Interface4
{
void Show();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace IOCTest
{
internal class Class4
{
[Dependency]
public Class3 _class3 { get; set; }
public Class4()
{
//Console.WriteLine($"{_class3.GetType().Name}被构造");
Console.WriteLine($"{this.GetType().Name}被构造");
}
public void Show()
{
Console.WriteLine($"{this.GetType().Name}--Show");
}
}
}
方法注入
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOCTest
{
internal interface Interface5
{
void Show();
// void Init(Class4 class4);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
namespace IOCTest
{
internal class Class5:Interface5
{
private Class4 _class4 { get; set; }
public Class5()
{
//Console.WriteLine($"{_class3.GetType().Name}被构造");
Console.WriteLine($"{this.GetType().Name}被构造");
}
[InjectionMethod]
public void Init(Class4 class4)
{
_class4 = class4;
}
public void Show()
{
Console.WriteLine($"{this.GetType().Name}--Show");
}
}
}