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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With