Resolve an instance of the default requested type from the container.
會將所指定的 class 產生一個 instance 並且將 Constructor 中的 parameter 注入
container.Resolve(typeof(HomeController))
public HomeController(Service service, Service2 service2)
{ this.service = service; this.service2 = service2;}
container 會將 Service 及 Service2 注入到 HomeController 中
但有個地方值得注意的。就是如果 HomeController 的 Constructor parameter 的 type 是 interface 時,就必需要注冊
container.RegisterType<IService, Service>();
否則會有錯誤產生
2. Singleton
底下以 RegisterInstance 的方來來注冊 IUser
protected void Application_Start()
{IUnityContainer container = new UnityContainer();
container.RegisterInstance<IUser>(new User() { Name = "Unity" });
CustomUnityControllerFactory factory = new CustomUnityControllerFactory(container);
ControllerBuilder.Current.SetControllerFactory(factory); RegisterRoutes(RouteTable.Routes);}
HomeController
Constructor 中有兩個參數 Service1, Service2
[HandleError]public class HomeController : Controller
{ Service1 service1; Service2 service2;public HomeController(Service1 service1, Service2 service2)
{ this.service1 = service1; this.service2 = service2;}
public ActionResult Index()
{ ViewData["Message"] = service1.Message(); ViewData["Message2"] = service2.Message(); return View();}
public ActionResult About()
{ return View();}
}
Service1
在呼叫 Message 後會改變 User.Name 的值
public class Service1 : IService
{ IUser user;public Service1(IUser user)
{ this.user = user;}
#region IService Memberspublic string Message()
{ string t = user.Name; user.Name = "Yes!! I'm Sigleton"; return t;}
#endregion}
Service2
public class Service2 : IService
{ IUser user;public Service2(IUser user)
{ this.user = user;}
#region IService Memberspublic string Message()
{ return user.Name;}
#endregion}
Reference
Unity framework with ASP.Net MVC Framework
沒有留言:
張貼留言