Can I embed a dependency in a ServiceStack request filter?

I can successfully inject dependencies into my ServiceStack services, but now I need to add the dependency to the query filter. However, it does not seem to work the same.

Here is my filter (it just checks if the source IP is in the approved list, this is the list I'm trying to enter):

public class CheckIPFilter : RequestFilterAttribute { private readonly IList<string> _IPAddresses = new List<string>(); public CheckIPFilter() { } public CheckIPFilter(IList<string> IPAddresses) { _IPAddresses = IPAddresses; } public override void Execute(ServiceStack.ServiceHost.IHttpRequest req, ServiceStack.ServiceHost.IHttpResponse res, object requestDto) { if (!_IPAddresses.Contains(req.UserHostAddress)) { var errResponse = DtoUtils.CreateErrorResponse("401", "Unauthorised", null); var responseDto = DtoUtils.CreateResponseDto(requestDto, new ResponseStatus("401", "Unauthorised")); var contentType = req.ResponseContentType; var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(contentType); res.ContentType = contentType; var serializationContext = new HttpRequestContext(req, res, responseDto); serializer(serializationContext, responseDto, res); res.EndRequest(); //stops further execution of this request return; } } } 

This is what is in my global.asax:

 var IPAddresses = new List<string>() { "99.99.99.99", "99.99.99.99", "99.99.99.99", "99.99.99.99" }; container.Register<IList<string>>(IPAddresses); 

_IPAddresses is always null.

I think I should miss something basic here. Is there a better way to approach this?

+6
source share
1 answer

Use property injection instead of constructor injection for filter attributes, as they are cloned and publicly accessible, and not created like anything created from IOC and automatically connected.

+4
source

Source: https://habr.com/ru/post/957135/


All Articles