1、Webapi框架下使用Autofac属性注入之----AuthorizeAttribute的属性注入
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public MyLog log { get; set; } //autofac注入的属性
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
{
log.Message("验证信息...");
}
}
2、在WebApiConfig.cs文件中添加配置代码:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
// Web API 路由
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//依赖注入初始化
AutofacBuilder.Init(config);
}
}
3、新建一个autofac依赖注入配置文件:AutofacBuilder.cs
public class AutofacBuilder
{
public static void Init(HttpConfiguration config)
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MyLog>().As<MyLog>(); //MyLog也可以写成接口 ==>> builder.RegisterType<MyLog>().As<IMyLog>();
//builder.RegisterFilterProvider();
builder.RegisterWebApiFilterProvider(config);
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces().AsSelf();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
Autofac依赖注入之AuthorizeAttribute属性注入---.net framework 4.5 Mvc5 WebApi