Unity here refers to the completion of dependency injection of unity rather than the game engine.
Originally the project completed dependency injection with spring.net, but Spring.net has been a long time no one to maintain, so Microsoft's official launch of Unity as a substitute for spring.net one of the best candidates.
Simple Console Demo:
Start with a new console app, and NuGet searches for unity and installs it.
usingSystem; usingUnity;usingunity.attributes;namespaceconsoleapp1{ Public classIndex {[Dependency] Public VirtualIuserservice UserService {Set;Get; } Public Static voidMain (string[] args) { varcontainer =NewUnityContainer (); Container. Registertype<iuserservice, userservice>(); Register Iuserservice UserService= Container. Resolve<iuserservice>(); Get Userservice.hello (); } } Public InterfaceIuserservice {voidHello (); } classUserservice:iuserservice { Public voidHello () {Console.WriteLine ("Hello"); } }}
Using Unity in asp:
1. New ASP. NET MVC application, NuGet installation Unity.mvc
2, the new class library BLL, IBLL, completed after the directory as follows:
3. BLL new USERSERVICE,IBLL New Iuserservice, implement Hello method
namespace ibll{ publicinterface iuserservice { string Hello (); }}
using IBLL; namespace bll{ publicclass userservice:iuserservice { public string Hello () { return"hello";}} }
4: Fill in the configuration in Global.asax.cs. Examples are as follows:
usingSYSTEM.WEB.MVC;usingSystem.Web.Optimization;usingSystem.Web.Routing;usingBLL;usingIBLL;usingUnity;usingUNITY.ASPNET.MVC;namespacewebapp{ Public classMvcApplication:System.Web.HttpApplication {protected voidApplication_Start () {arearegistration.registerallareas (); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (Bundletable.bundles); varcontainer =Buildunitycontainer (); Customize the Buildunitycontainer method to get the container dependencyresolver.setresolver (NewUnitydependencyresolver (container)); } Iunitycontainer Buildunitycontainer () {UnityContainer container=NewUnityContainer (); Container. Registertype<iuserservice, userservice>();returncontainer; } }}
5. Obtain the UserService class in control and use
usingSYSTEM.WEB.MVC;usingIBLL;namespacewebapp.controllers{ Public classHomecontroller:controller {PrivateIuserservice UserService; PublicHomeController (Iuserservice userservice) { This. UserService =UserService; Using constructor injection } PublicActionResult Index () {stringstr =Userservice.hello (); returnContent (str); } }}
This completes one of the simplest MVC demos.
Other details such as using configuration files, using other methods of injection, and so on, can refer to this post: https://www.cnblogs.com/qqlin/archive/2012/10/18/2720828.html
Unity Official Document: Https://msdn.microsoft.com/en-us/library/ff649564.aspx
Unity (C # IOC framework) Usage Summary