Base solution for your next web application
Open Closed

How to use the ‘Dependency Injection’ in Mvc's ActionFilter? #811


User avatar
0
wddpct created

Hi.I have to admit that I spent a lot of time to write these words(sorry,my English is poor) In the ActionFilter of Mvc, I can't use constructor or property Injection, cuz there are no injection points. Finally, I choose the method which can work. When I defined a interface such as ITest which contain the method like 'GetName()', and I defined the Test which inherited the former. I write the code like 'IocManager.IocContainer.Register( Component.For<ITest >());' in the 'Initialize' of Module's methods. And I resolve the ITest in my action filter like 'var test = IocManager .Instance.Resolve< ITestService >().GetName();', Yes, it can work.But I want to know, how do you deal with it when you want to use the services' methods or some interface by injected!!! thanks a lot.!!!


2 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Using IocManager .Instance.Resolve is a good way. But I suggest ResolveAsDisposable method since you should always release a class if you resolved it manually.

    Another way: You can register filter attribute to dependency injection and register your filter like that: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/blob/master/src/Abp.Web.Api/WebApi/AbpWebApiModule.cs#L82">https://github.com/aspnetboilerplate/as ... ule.cs#L82</a>

  • User Avatar
    0
    wddpct created

    <cite>hikalkan: </cite> Using IocManager .Instance.Resolve is a good way. But I suggest ResolveAsDisposable method since you should always release a class if you resolved it manually.

    Another way: You can register filter attribute to dependency injection and register your filter like that: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate/blob/master/src/Abp.Web.Api/WebApi/AbpWebApiModule.cs#L82">https://github.com/aspnetboilerplate/as ... ule.cs#L82</a>

    Thanks a lot! Actually,I found some other questions in using abp's Context.set<TEntity>().Methods Like AddRange and so on . Sometimes,yes,sometimes, there are no reactions.No successful ,no fail tips even thouth I used 'Try Catch' to grab the ex. And sometimes it works. There is my code. Could I get help from you? public async Task< OperationResult> ImportSchoolList(List<AbpSchool> schoolList) { var operatioResult = new OperationResult();

            try
            {
                Context.Set&lt;AbpSchool&gt;().AddRange(schoolList);
    
                operatioResult.AppendData = await Context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
    
                LoggerHelper.Error(ex.Message, ex);
            }
            
            return operatioResult;
        }