在項目中引入Unity,建立一個接口IWork跟一個繼承IWork接口的Work類
public interface IMyWork { void Work(); } public class MyWork : IMyWork { public void Work() { Console.WriteLine("Hello World!"); } }
unity的簡單使用分三步
static void Main(string[] args) { UnityContainer container = new UnityContainer();//創建IOC容器 container.RegisterType<IMyWork, MyWork>();//注冊(Register) var myWork = container.Resolve<IMyWork>();//獲取(Resolve) myWork.Work();//hello world Console.ReadKey(); }
參考Unity ASP.NET MVC 將UnityContaniner封裝 類名也叫做UnityConfig(參考Unity4.0的使用),進行職責分離,分離注冊與獲取,同時進行單例與延遲加載(在后面的文章還會提到)
public class UnityConfig : IInstance<UnityConfig>, IServiceProvider { #region Unity Container private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() => { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// <summary> /// Gets the configured Unity container. /// </summary> public static IUnityContainer GetConfiguredContainer() { return container.Value; } #endregion /// <summary>Registers the type mappings with the Unity container.</summary> /// <param name="container">The unity container to configure.</param> /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks> public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. //container.LoadConfiguration(); // TODO: Register your types here // container.RegisterType<IProductRepository, ProductRepository>(); container.RegisterType<IMyWork, MyWork>(); } public object GetService(Type serviceType) { return GetConfiguredContainer().Resolve(serviceType); } public T GetService<T>() { return (T)GetService(typeof(T)); } }
public class IInstance<T> where T : new() { private static readonly T instance = new T(); public static T Instance { get { return instance; } } }
最后的調用
class Program { static void Main(string[] args) { var myWork = UnityConfig.Instance.GetService<IMyWork>();//獲取(Resolve) myWork.Work();//hello world Console.ReadKey(); } }
以上是本人比較初級的處理,主要用於本人學習Unity的一個記錄