Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inject a dependency into a ServiceStack Request Filter?

I can successfully inject dependencies into my ServiceStack services but now I have a need to inject a dependency into a Request Filter. However this does not appear to work the same way.

Here's my filter (it simply checks whether the source IP is in an approved list; it is this list I'm trying to inject):

 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's 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 guess I must be missing something basic here. Is there a better way of approaching this?

like image 271
Simon Avatar asked Oct 31 '13 16:10

Simon


1 Answers

Use property injection instead of constructor injection for filter attributes, since they are cloned and public properties auto-wired and not created like everything else that is instantiated from the IOC and auto-wired.

like image 189
mythz Avatar answered Sep 21 '22 19:09

mythz