.net framework webapi + autofac

.net framework 4.7.2

1,引用

Autofac 6.3.0

Autofac.WebApi2 6.1.0

2,Global.asax

using Autofac;
using Autofac.Integration.WebApi;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

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

var builder = new ContainerBuilder();
//Assembly asseambly_BLL = Assembly.Load("ClassLibrary1");
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
//builder.RegisterAssemblyTypes(asseambly_BLL).AsImplementedInterfaces().PropertiesAutowired();

builder.RegisterAssemblyTypes(Assembly.Load("ClassLibrary1"))
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();

var container = builder.Build();

//System.Web.Mvc.DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

}


}
}

3,接口请求

using ClassLibrary1;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApplication4.Controllers
{
public class TestAutofacController : ApiController
{
public ITestService _testService;
public TestAutofacController(ITestService testService)
{
this._testService = testService;
}

[HttpGet]
[Route("TestAutofac/GetTest")]
public string GetTest()
{
var result = _testService.GetList();
return JsonConvert.SerializeObject(result);
}
}
}

 

posted @ 2022-04-23 16:39  元点  阅读(201)  评论(0编辑  收藏  举报