尝试将属性注入我的自定义AuthorizeAttribute,但此属性始终为null。这个注册错了吗?
public class AuthenticateAttribute : AuthorizeAttribute
{
public IAuthenticationService authenticationService { get; set; }
public UserTypes UserType;
public AuthenticateAttribute()
{
}
}
从全球Asax调用
public static void InitializeDependencies()
{
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterAssemblyTypes(Assembly.Load("BusinessServices"))
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
builder.RegisterAssemblyTypes(Assembly.Load("BusinessEntities"))
.Where(t => t.Name.EndsWith("Helper"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
builder.Register(x => new ApiExceptionHandler(x.Resolve<ILogService>())).AsWebApiExceptionFilterFor<ApiController>().InstancePerLifetimeScope();
builder.RegisterType<AuthenticateAttribute>().PropertiesAutowired().InstancePerLifetimeScope();
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
身份验证服务
public class AuthenticationService : IAuthenticationService
{
private readonly IUnitOfWork unitOfWork;
private readonly IAutoMapperHelper mapper;
public AuthenticationService(IUnitOfWork _unitOfWork, IAutoMapperHelper _mapper)
{
unitOfWork = _unitOfWork;
mapper = _mapper;
}
}
我不能使用authenticate属性作为构造函数注入,因为我不能在方法上使用它。
[Authenticate] //How can i pass authenticationService parameter to it, if i use constructor injection?
[HttpPost]
public async Task<ConnectSocialPlatformsResponseModel> ConnectSocialPlatforms(ConnectSocialPlatformsRequestModel model)
{
if (ModelState.IsValid)
return await authenticationService.ConnectSocialPlatforms(model);
else
return validationHelper.CreateResponse<ConnectSocialPlatformsResponseModel>(ModelState);
}