there unity It means to complete dependency injection unity Not the game engine .

The original project completion dependency injection is, however It's been a long time since people maintained , So Microsoft officially launched Unity Become a substitute for One of the best candidates for .

Simple console demo:

First, create a new console application ,nuget Search for unity And install .

using System;
using Unity;
using Unity.Attributes; namespace ConsoleApp1
public class Index
{ [Dependency]
public virtual IUserService UserService { set; get; } public static void Main(string[] args)
var container = new UnityContainer();
container.RegisterType<IUserService, UserService>(); // register
IUserService userService = container.Resolve<IUserService>(); // obtain
} public interface IUserService
void Hello();
} class UserService : IUserService
public void Hello()

stay mvc Use in unity:

1、 newly build mvc application ,nuget install unity.mvc

2、 The new library BLL、IBLL, After completion, the contents are as follows :

3、BLL newly build UserService,IBLL newly build IUserService, Realization Hello Method

namespace IBLL
public interface IUserService
string Hello();
} }
using IBLL;

namespace BLL
public class UserService:IUserService
public string Hello()
return "hello";

4: stay Global.asax.cs Fill in the configuration . Examples are as follows :

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BLL;
using IBLL;
using Unity;
using Unity.AspNet.Mvc; namespace WebApp
public class MvcApplication : System.Web.HttpApplication
protected void Application_Start()
BundleConfig.RegisterBundles(BundleTable.Bundles); var container = BuildUnityContainer(); // Customize BuildUnityContainer Method , Get the container
DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } IUnityContainer BuildUnityContainer()
UnityContainer container = new UnityContainer();
container.RegisterType<IUserService, UserService>();return container;

5、 stay Control gain UserService Class and use

using System.Web.Mvc;
using IBLL; namespace WebApp.Controllers
public class HomeController : Controller
private IUserService UserService;public HomeController(IUserService userService)
this.UserService = userService; // Use constructor Injection
} public ActionResult Index()
string str = UserService.Hello();
return Content(str);
} }

And that's the simplest of all mvc demo.

Other things like using configuration files 、 Use other methods to inject and other detailed operations , You can refer to this post :

unity Official documents :

unity(c# ioc frame ) Use more related articles in the summary

  1. .Net IOC frame

    CastleWindsor See :CastleWindsor | .Net IOC frame AutoFace See :AutoFace | .Net IOC frame Unity See :Unity | .Ne ...

  2. Use Microsoft Of IoC frame :Unity Come on .NET Application decoupling

    1.IoC/DI brief introduction IoC namely Inversion of Control,DI namely  Dependency Injection, The former Chinese meaning is inversion of control , Dependency injection , It can be understood as a programming pattern , detailed ...

  3. dependency inversion Ioc and unity,autofac,castle Framework tutorial and comparison

    1. The concept of dependency inversion IoC Pattern ( rely on . Dependency inversion . Dependency injection . Inversion of control ) 2. Depending on the way of inversion ...

  4. MVC4 be based on Unity Ioc Framework of the ControllerFactory

    First introduce Untiy frame . Can be in NuGet Package Manager directly installed in . newly build Inherit DefaultControllerFactory   Of UnityControllerFactory: Rewrite virtual methods GetC ...

  5. Today's research Unity Ioc frame

    Today's research Unity Ioc frame , For more than two hours . Error is reported when running , Over and over again , The configuration file , There's no problem with the code , I've written it several times . Finally, I read the wrong news carefully ,config The file was not generated to the directory ……… ...

  6. Major mainstream .Net Of IOC Framework performance test comparison

    Autofac Download address : Castle Windsor Download address : ...

  7. .NET The most popular in this field IOC One of the frames Autofac

    One . Preface Autofac yes .NET The most popular in this field IOC One of the frames , Microsoft Orchad Open source programs use Autofac,Nopcommerce Open source programs are also used Autofac. Orchad and Nopcomm ...

  8. IOC frame Ninject practice

    Original address : IOC frame Ninject practice One . control ...

  9. Open source written by Chinese people .net Ioc frame ——My.Ioc brief introduction

    My.Ioc It is an open source developed by the author IoC/DI frame , The download address is here . It has the following characteristics : Efficient In terms of means of realization ,My.Ioc By using generics . cache . Generate code dynamically . Delay registration . Try to use abstract classes instead of interfaces ...

Random recommendation

  1. unity File parsing and version control

    Just beginning to use unity When doing development , Get a sample project and upload it first SVN, And then I'll make some changes myself , I found a lot of files have changed , Only then can we know that there are many locally generated files , There's no need to upload , But I don't know what needs to be shared . And then I was obsessed with revising ...

  2. MVC Mode to qq E-mail

    Send the password saved in the database to qq In the mailbox . With ssm frame , Among them config The file should be configured first . Use of jar Package has a gson-2.2.1.jar,gson.jar,mail.jar,activat ...

  3. Not registered on the local computer “Microsoft.Jet.OLEDB.4.0

    A tool was modified yesterday , After compiling, the machine runs normally , But it can't be executed on the server , Tips : message:GetOleDbSchemaTable requires an open and available Conn ...

  4. 【php Way of learning 】 String manipulation

            Whatever language you learn , String manipulation is a necessary foundation . learn php When I'm with you, I'll be with you unconsciously C# Compare , It's not so easy to use , Some of the names are quite different , In addition, many functions are named in short form. I really don't know what to do under Baidu ...

  5. POJ 1724 ROADS(BFS+ Priority queue )

    Topic link The question : Seek from 1 City to n The shortest path to the city . But each path has two attributes , One is a long way , One is cost . Ask for at the expense of K Inside , Find the shortest path . Ideas : It seems that there are many ways to solve this problem , I used it BFS+ Priority queue . Miss Cui has never changed for a thousand years ...

  6. git Basic use notes

    One . The second installation step is omitted . function “Git Bash“ Enter... In the open window :ssh-keygen -t rsa -C ""  Will prompt SSH Public Keys Storage bit ...

  7. PHP.INI List of common settings ( Continuous updating )

    Problems encountered or found in the process of programming , It will be updated continuously : 1. break var_dump The display bottleneck of php In the development environment , Installed xdebug After module ,var_dump() The output will be easier to see , But by default ,var_d ...

  8. Debian/Ubuntu Cleaning up hard disk space 8 Tips

    1. Delete the remaining configuration files Usually Debian/Ubuntu There are two commands to delete a package sudo apt-get remove <package-name> sudo apt-get purge ...

  9. zookeeper Installation, use and working principle analysis

    1. Zookeeper Concept introduction Zookeeper It's a distributed coordination service : It is to provide coordination services for users' distributed applications , It's the manager of the cluster , Monitoring the status of each node in the cluster , According to the feedback submitted by the node, carry out the next reasonable operation . ...

  10. tomcat Startup error invalid LOC header

    tomcat Startup error invalid LOC header,run as maven test  No report error , Just a warning : 'build.plugins.plugin.version' for org.ap ...