Base solution for your next web application
Open Closed

custom attribute and dependency injection #1597


User avatar
0
mbit created

Hi,

to implement a custom api for external use i want to implement hmac authentification via a custom attribute like this:

namespace xxx.Api.Controllers
{
	[Audited]
	[MeHmacAuthentication]
	public class ExportController : MeApiControllerBase
...

In a standalone mvc app all worked, but now i migrate the whole project to abp style.

In the implementation of the attribute i do: (McHmacAuthenticationAttribute is a common baseclass doing the most things)

namespace xxx.Authentication
{
    
    public class MeHmacAuthenticationAttribute : McHmacAuthenticationAttribute
    {
        private readonly IMeApiKeyAppService _apikeyService;
		public MeHmacAuthenticationAttribute(IMeApiKeyAppService apikeyService)
        {
            _apikeyService = apikeyService;

            ListResultOutput<MeApiKeyListDto> keys = _apikeyService.GetKeys();
...

but _apikeyService does not get injected. I tried to manually register:

public class MeApiModule : AbpModule
	{
		public override void PreInitialize()
		{
			Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
		}

		public override void Initialize()
		{
			IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
			IocManager.Register<IMeApiKeyAppService, MeApiKeyAppService>(DependencyLifeStyle.Transient);
		}

		public override void PostInitialize()
		{
			base.PostInitialize();
		}

but this did not change anything.

can you please guide me to thi right direction to do this

thanks in advance Martin


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Does your MeHmacAuthenticationAttribute have a parameterless constructor ? Otherwise you couldn't use it like this [MeHmacAuthentication] I think :).

    In MVC you cannot inject anything to attributes. You have two options,

    1 - Resolve IMeApiKeyAppService manually

    var meApiKeyAppService = IocManager.Instance.Resolve<IMeApiKeyAppService >();
    

    in your attribute when you need it. Then you should release it after you are done with it like this

    IocManager.Instance.Release(meApiKeyAppService );
    

    2 - You can create a web api filter and add it to web api filters. For this one, you can take a look at AbpApiAuditFilter in ABP's source code and it's usage.