zoukankan      html  css  js  c++  java
  • Autofac in webapi2

    安装包:Autofac.webapi2 

    注意:

     install-package autofac.webapi2 (注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。”错误。)

    在global 中 的Application_Start()添加

    var builder = new ContainerBuilder();
    //builder.RegisterControllers(Assembly.GetExecutingAssembly()); //Register MVC Controllers
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
    //Register any other components required by your code....
    builder.RegisterType<UserTest2>().As<IUserTest>();
    var container = builder.Build();

    // DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
    GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver

    UserTest接口:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace webapiTest
    {
    public interface IUserTest
    {
    int GetI(int i);
    }

    public class UserTest : IUserTest
    {
    public int GetI(int i)
    {
    return i;
    }
    }

    public class UserTest2 : IUserTest
    {
    public int GetI(int i)
    {
    return i*i;
    }
    }
    }

    使用:

    public class DefaultController : ApiController
    {
    private IUserTest _userTest;
    public DefaultController(IUserTest userTest)
    {
    _userTest = userTest;
    }

    // GET: api/Default/5
    public int Get(int id)
    {
    return _userTest.GetI(id);
    }

    }

    参考:

    http://autofac.readthedocs.io/en/latest/integration/webapi.html#quick-start

    https://weblogs.asp.net/shijuvarghese/dependency-injection-in-asp-net-web-api-using-autofac

    https://stackoverflow.com/questions/26358287/how-do-i-resolve-web-api-controllers-using-autofac-in-a-mixed-web-api-and-mvc-ap

     https://github.com/autofac/Examples

    扩展:container 需要管理起来的

    http://www.cnblogs.com/niuww/p/5649632.html

  • 相关阅读:
    程序员都必读
    ia-64 vs x86-64
    Linux内核学习
    开源liscense对比
    列存储
    大数据科普
    [USACO1.5]数字三角形
    [USACO08FEB]酒店Hotel
    数的划分
    CodeForce 18D
  • 原文地址:https://www.cnblogs.com/kingreatwill/p/7070203.html
Copyright © 2011-2022 走看看