SimpleInjector与MVC4集成,与Web Api集成,以及通过属性注入演示

 

1,与MVC集成

http://simpleinjector.codeplex.com/wikipage?title=Integration%20Guide&referringTitle=Home
我们自己建个MVC4项目测试

1.1 nuget

只需要安装Mvc的集成即可,其它的依赖会自动安装:

Install-Package SimpleInjector.Integration.Web.Mvc

1.2 Global.asax:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
             
            //按如下步骤添加
            // 1. Create a new Simple Injector container
            var container = new Container();
 
            // 2. Configure the container (register)
            //container.Register<IUserService, UserService>(Lifestyle.Transient);
            //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
            //随便写个例子测试,名字就不计较了,Lifestyle的区别自行查文档
            container.Register<Iaaa, aaa>(Lifestyle.Transient);
 
            // 3. Optionally verify the container's configuration.
            container.Verify();
 
            // 4. Store the container for use by Page classes.
            //WebApiApplication.Container = container;
            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
 
            // 5. register global filters //如果有注册全局过滤器的需要加此节点,和下面注释掉的方法
            //RegisterGlobalFilters(GlobalFilters.Filters, container);
        }
 
        //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
        //{
        //}
    }

1.3 测试接口和方法的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public interface Iaaa
{
    int a { get; set; }
    string hello(string str);
}
 
public class aaa : Iaaa
{
    public aaa()
    {
        a = DateTime.Now.Millisecond;
    }
    public int a { get; set; }
 
    public string hello(string str)
    {
        return "hello " + str + " timestamp: " + a;
    }
}

1.4 到一个controller里面测试

注意私有变量,和构造函数的使用即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class testController : Controller
{
    private Iaaa _srv;
 
    public testController(Iaaa srv)
    {
        _srv = srv;
    }
    public string Index(string id)
    {
        return _srv.hello(id);
    }
}

访问/test/myname 正确输出"hello myname timestamp 234"
其实跟官网的一模一样:http://simpleinjector.codeplex.com/

2,与WebApi集成

http://simpleinjector.codeplex.com/wikipage?title=Web%20API%20Integration&referringTitle=Integration%20Guide
在同一个项目里测试就行了,更好演示与mvc和与web api集成的区别,所以也不需要新建项目,及添加引用了

2.1 新建一个webapi的控制器tst

基本上是复制test控制器的代码,很简单:

1
2
3
4
5
6
7
8
9
10
11
12
public class tstController : ApiController
{
    private Iaaa _srv;
    public tstController(Iaaa srv)
    {
        _srv = srv;
    }
    public string get(string id)
    {
        return _srv.hello(id);
    }
}

2.2 测试失败

访问/api/tst/aaa,却直接报错Type 'WebApplication1.Controllers.tstController' does not have a default constructor,按照上面给的官网的集成说明提示更改Global.asax即可,改后如下(见修改点1和2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
             
            //按如下步骤添加
            // 1. Create a new Simple Injector container
            var container = new Container();
 
            // a.1 webapi, frist register controller 修改点1
            var services = GlobalConfiguration.Configuration.Services;
            var controllerTypes = services.GetHttpControllerTypeResolver()
                .GetControllerTypes(services.GetAssembliesResolver());
 
            // register Web API controllers (important! http://bit.ly/1aMbBW0)
            foreach (var controllerType in controllerTypes)
            {
                container.Register(controllerType);
            }
 
            // 2. Configure the container (register)
            //container.Register<IUserService, UserService>(Lifestyle.Transient);
            //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
            //随便写个例子测试,名字就不计较了,Lifestyle的区别自行查文档
            container.Register<Iaaa, aaa>(Lifestyle.Transient);
 
            // 3. Optionally verify the container's configuration.
            container.Verify();
 
            // 4. Store the container for use by Page classes.
            //WebApiApplication.Container = container;
            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
             
            // a.2 webapi  按照文档,写在verify()后面 修改点2
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
 
            // 5. register global filters //如果有注册全局过滤器的需要加此节点,和下面注释掉的方法
            //RegisterGlobalFilters(GlobalFilters.Filters, container);
        }
 
        //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
        //{
        //}
    }

再测试就通过了

3,通过属性注入

我们上面演示的都是通过构造器注入,关于属性注入,SimpleInjector做了严格限制,但是还是支持,需要显式注入:http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios&referringTitle=Home#Property-Injection
直接演示一种最简单的方法吧:

1
2
3
container.RegisterInitializer<HandlerBase>(handlerToInitialize => {
    handlerToInitialize.ExecuteAsynchronously = true;
});

所以完成版的Global.asax如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
protected void Application_Start()
       {
           AreaRegistration.RegisterAllAreas();
           GlobalConfiguration.Configure(WebApiConfig.Register);
           FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
           RouteConfig.RegisterRoutes(RouteTable.Routes);
           BundleConfig.RegisterBundles(BundleTable.Bundles);
            
           //按如下步骤添加
           // 1. Create a new Simple Injector container
           var container = new Container();
 
           // a.1 webapi, frist register controller 修改点1
           var services = GlobalConfiguration.Configuration.Services;
           var controllerTypes = services.GetHttpControllerTypeResolver()
               .GetControllerTypes(services.GetAssembliesResolver());
 
           // register Web API controllers (important! http://bit.ly/1aMbBW0)
           foreach (var controllerType in controllerTypes)
           {
               container.Register(controllerType);
           }
 
           // 2. Configure the container (register)
           //container.Register<IUserService, UserService>(Lifestyle.Transient);
           //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
           //随便写个例子测试,名字就不计较了,Lifestyle的区别自行查文档
           container.Register<Iaaa, aaa>(Lifestyle.Transient);
           container.RegisterInitializer<tstController>(c => c.s2 = new bbb());//显然,其实就是手动指定
 
           // 3. Optionally verify the container's configuration.
           container.Verify();
 
           // 4. Store the container for use by Page classes.
           //WebApiApplication.Container = container;
           System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            
           // a.2 webapi 修改点2,按照文档,写在verify()后面
           GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
 
           // 5. register global filters //如果有注册全局过滤器的需要加此节点,和下面注释掉的方法
           //RegisterGlobalFilters(GlobalFilters.Filters, container);
       }
 
       //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
       //{
       //}
   }

完整版的webapi的controller如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class tstController : ApiController
{
    private Iaaa _srv;
    public Ibbb s2 { get; set;} //注意s2,是一个属性
 
    public tstController(Iaaa srv)
    {
        _srv = srv;
    }
    //演示构造函数注入
    public string get(string id)
    {
        return _srv.hello(id);
    }
   //演示属性注入
    public string get()
    {
        return s2.curtime;
    }
}

取名字随意了点,包涵。
    访问/api/tst/,得到current time is: 2013-12-15T23:06:0,我们并没有在构造器中初始化Ibbb,但已经是从aaa对象里取到了值,测试通过。

4,示例代码

git clone https://github.com/walkerwzy/simpleinjectorSample.git

 
分类: c#.net MVC
标签: DIsimpleinjector

SimpleInjector与MVC4集成,与Web Api集成,以及通过属性注入演示的更多相关文章

  1. ASP.NET Web API 2 中的属性路由使用(转载)

    转载地址:ASP.NET Web API 2 中的属性路由使用

  2. Web API 2中的属性路由

    Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...

  3. ASP.NET Web API 2中的属性路由(Attribute Routing)

    如何启用属性路由并描述属性路由的各种选项? Why Attribute Routing? Web API的第一个版本使用基于约定的路由.在这种类型的路由中,您可以定义一个或多个路由模板,这些模板基本上 ...

  4. Web API集成Azure AD认证

    1.声明的介绍 基于角色的授权管理,适用于角色变化不大,并且用户权限不会频繁更改的场景. 在更复杂的环境下,仅仅通过给用户分配角色并不能有效地控制用户访问权限. 基于声明的授权有许多好处,它使认证和授 ...

  5. ASP.NET MVC4中调用WEB API的四个方法

    http://tech.it168.com/a2012/0606/1357/000001357231_all.shtml [IT168技术]当今的软件开发中,设计软件的服务并将其通过网络对外发布,让各 ...

  6. MVC4 WebAPI(二)——Web API工作方式

    http://www.cnblogs.com/wk1234/archive/2012/05/07/2486872.html 在上篇文章中和大家一起学习了建立基本的WebAPI应用,立刻就有人想到了一些 ...

  7. Asp.Net Web API 2第八课——Web API 2中的属性路由

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 路由就是Web API如何 ...

  8. ASP.NET Web API - 使用 Castle Windsor 依赖注入

    示例代码 项目启动时,创建依赖注入容器 定义一静态容器 IWindsorContainer private static IWindsorContainer _container; 在 Applica ...

  9. Web Api集成Swagger

    WebApi集成Swagger 1.新建一个WebApi空项目 2.新建一个Person实体类: public class Person { public int ID { get; set; } p ...

随机推荐

  1. [ Talk is Cheap Show me the CODE ] : jQuery Mobile工具栏

    [ Talk is Cheap Show me the CODE ] : jQuery Mobile工具栏 Written In The Font " Wirte less Do more& ...

  2. C#中的Virtual

    在 C# 中,派生类可以包含与基类方法同名的方法. 基类方法必须定义为 virtual. 如果派生类中的方法前面没有 new 或 override 关键字,则编译器将发出警告,该方法将有如存在 new ...

  3. 【程序员小助手】Emacs,最强编辑器,没有之一

    内容简介 1.Emacs简介 2.Emacs三个平台的安装与配置 3.自动补全插件 4.小编的Emacs配置文件 5.常用快捷方式 6.和版本控制系统的配合(以SVN为例) [程序员小助手]系列 在这 ...

  4. 警报C++精密整数除法计算损失

    非常偶然发现了一个精度损失的问题,简单来说: 有表达式: l = i/30 + j/40 + k/25, 求当{i,j,k} = {50,85,27}时l的值,非常easy,用计算器立即能够算出答案为 ...

  5. Chapter 1 Securing Your Server and Network(1):选择SQL Server运行账号

    原文:Chapter 1 Securing Your Server and Network(1):选择SQL Server运行账号 原文出处:http://blog.csdn.net/dba_huan ...

  6. 【足迹C++primer】48、函数引用操作符

    函数引用操作符 struct absInt { int operator()(int val) const { cout<<val<<"<->!!!&qu ...

  7. StackExchange.Redis 使用-配置 (四)

    Configurationredis有很多不同的方法来配置连接字符串 , StackExchange.Redis 提供了一个丰富的配置模型,当调用Connect 或者 ConnectAsync 时需要 ...

  8. DM8168 新三板系统启动

    DM8168从补丁到系统的新董事会开始折腾了20天,最终完成,高校是累的东西,导师只焊接机10一个BGA,其他人则手. 前段时间启动操作系统时,到了Starting Matrix GUI applic ...

  9. Sonar——代码质量管理平台

    Sonar——代码质量管理平台 一.基本认识 Sonar (SonarQube)是一个开源平台,用于管理源代码的质量. Sonar 不只是一个质量数据报告工具,更是代码质量管理平台.通过插件机制,So ...

  10. window.open的小技巧分享(转)

    今天再次谈起window.open是因为发现了一个比较好玩的小技巧,详细内容我们稍后详细说明.       聊到window.open,不得不说明一下他的使用方法,主要有两种形式:   window. ...