大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > ASP.NET技巧 > autofac使用详解

autofac使用详解(3)

关键词:autofac使用详解  阅读(4019) 赞(12)

[摘要]本文是对autofac使用笔记的讲解,对学习ASP.NET编程技术有所帮助,与大家分享。

下面是webapiconfig文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiIoc.App_Start;

namespace WebApiIoc
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //注册webapi和mvc容器
            autofaconfig.Initialize(config);
        }
    }
}

最后是global文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using WebApiIoc.App_Start;

namespace WebApiIoc
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
    }
}

在apicontroller和MVCcontroller里面都是通过构造函数注入的方式实现的下面贴出来代码

这个是MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Iservices;
using Microsoft.Ajax.Utilities;

namespace WebApiIoc.Controllers
{
    public class HomeController : Controller
    {
        private IOneServices _oneServices;


        
        public HomeController(IOneServices oneServices)
        {
            _oneServices = oneServices;

        }

        public ActionResult Index()
        {
            var sum = _oneServices.sum(10, 20);


            var aa = DependencyResolver.Current.GetService<IOneServices>();

            ; ViewBag.Title = sum;

            return View();
        }
    }
}


相关评论