ASP.NET MVC4中使用Ninject
1 //注册Ninject依赖注入全局解析器
2 GlobalConfiguration.Configuration.DependencyResolver = new System.Web.Http.Dependencies.NinjectDependencyResolver(new Ninject.StandardKernel());
辅助类
1 using BLL;
2 using IBLL;
3 using Ninject;
4 using System.Web.Http.Dependencies;
5
6 namespace System.Web.Http.Dependencies
7 {
8 //Author:GaoBingBing
9 public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
10 {
11 [Ninject.Inject]
12 private IKernel kernel;
13 public NinjectDependencyResolver()
14 {
15
16 }
17 public NinjectDependencyResolver(IKernel kernel)
18 {
19 this.kernel = kernel;
20 this.kernel.Settings.InjectNonPublic = true;
21 this.AddBinds();
22 }
23
24 private void AddBinds()
25 {
26
27 //由此添加你的注入
28 this.kernel.Bind<IXX>().To<XX>();
29 }
30 //开始处理
31 public IDependencyScope BeginScope()
32 {
33 return new NinjectDependencyScope(this.kernel.BeginBlock());
34 }
35
36
37
38 }
39 }
1 using Ninject.Activation;
2 using Ninject.Parameters;
3 using Ninject.Syntax;
4 using System;
5 using System.Collections.Generic;
6 using System.Linq;
7 using System.Web.Http.Dependencies;
8
9 namespace System.Web.Http.Dependencies
10 {
11 //Author:GaoBingBing
12 public class NinjectDependencyScope : IDependencyScope
13 {
14 protected IResolutionRoot resolutionRoot;
15 public NinjectDependencyScope()
16 {
17
18 }
19 public NinjectDependencyScope(IResolutionRoot resolutionRoot)
20 {
21 this.resolutionRoot = resolutionRoot;
22 }
23 public object GetService(Type serviceType)
24 {
25 return resolutionRoot.Resolve(this.CreateRequest(serviceType)).SingleOrDefault();
26 }
27
28 public IEnumerable<object> GetServices(Type serviceType)
29 {
30 return this.resolutionRoot.Resolve(this.CreateRequest(serviceType));
31 }
32 private IRequest CreateRequest(Type serviceType)
33 {
34 return resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
35 }
36 public void Dispose()
37 {
38 this.resolutionRoot = null;
39 }
40 }
41 }
1 //Author:GaoBingBing
2 public class DIConfig
3 {
4 public static T CreateInstance<T>() where T : class
5 {
6 System.Web.Http.Dependencies.IDependencyResolver resolver = System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver;
7 return resolver.BeginScope().GetService(typeof(T)) as T;
8 }
9
10 }
private IXX _x=DIConfig.CreateInstance<IXX>();
上一篇: 搞笑教授
下一篇: 圣诞节送温馨 最适合送礼智能手机推荐
推荐阅读
-
Asp.net Core中如何使用中间件来管理websocket
-
asp.net使用FCK编辑器中的分页符实现长文章分页功能
-
ASP.NET中根据XML动态创建使用WEB组件
-
asp.net mvc4中bootstrap datetimepicker控件的使用
-
ASP.NET中Ajax怎么使用
-
ASP.NET mvc4中的过滤器的使用
-
ASP.NET MVC4使用MongoDB制作相册管理
-
灵活掌握Asp.net MVC中GridView的使用方法
-
ASP.NET MVC4中使用Html.DropDownListFor的方法示例
-
HighCharts图表控件在ASP.NET WebForm中的使用总结(全)