0

I have a custom authorize attribute like this :

public class AuthorizeApplicationAttribute : AuthorizeAttribute {

    private MainServiceSoapClient client;

    public AuthorizeApplicationAttribute() {
        this.client = new MainServiceSoapClient();
    }

    public AuthorizeApplicationAttribute(MainServiceSoapClient client) {
        this.client = client;
    }

    protected override bool IsAuthorized(HttpActionContext actionContext) {
        if (!base.IsAuthorized(actionContext)) return false;
        var currentUser = System.Web.Security.Membership.GetUser();
        if (currentUser == null) return false;
        var userId = (int)currentUser.ProviderUserKey;
        return client.HasPermission(userId);
    }

}

which I register in WebApiConfig as :

public class WebApiConfig {
    public static void Register(HttpConfiguration config) {

        // Web API configuration and services
        config.Filters.Add(new AuthorizeApplicationAttribute());
        // more configuration ...

    }

}

but AuthorizeAttribute doesn't have a dispose, I can call the constructor with the soap client instance, but then I'm not sure where to dispose it.

FYI: I'm not using a IoC container. Trying to learn how to make it manually.

This example uses a SoapClient but I have the same question about a DbContext while I can live without disposing DbContext and don't think not disposing a WCF Client will be that good.

Bart Calixto
  • 19,210
  • 11
  • 78
  • 114

2 Answers2

1

Use a using statement inside your IsAuthorized method to initialize and Dispose when needed instead of initializing in constructor.

If you ever need dependency injection then you can use Property Injection.

This question has two answers with Ninject and StructureMap How to use dependency injection with an attribute?

Community
  • 1
  • 1
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
  • 1
    using is not a valid way for disposing a wcf client because it can end in a faulted state. How to use property injection in this case? can you provide and example? – Bart Calixto Aug 22 '14 at 00:42
1

Solution to this question might give you exactly what you want:

What is the best workaround for the WCF client `using` block issue?

Community
  • 1
  • 1