开发者

How to dispose of custom object from within custom membership provider

I have created my custom MembershipProvider. I have used an instance of the class DBConnect within this provider to handle database functions. Please look at the code below:

public class SGIMembershipProvider : MembershipProvider
{
    #region "[ Property Variables ]"
    private int newPasswordLength = 8;
    private string connectionString;
    private string applicationName;
    private bool enablePasswordReset;
    private bool enablePasswordRetrieval;
    private bool requiresQuestionAndAnswer;
    private bool requiresUniqueEmail;
    private int maxInvalidPasswordAttempts;
    private int passwordAttemptWindow;
    private MembershipPasswordFormat passwordFormat;
    private int minRequiredNonAlphanumericCharacters;
    private int minRequiredPasswordLength;
    private string passwordStrengthRegularExpression;
    private MachineKeySection machineKey; 

    **private DBConnect dbConn;**
    #endregion

.......

    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        if (!ValidateUser(username, oldPassword))
            return false;

        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);

        OnValidatingPassword(args);

        if (args.Cancel)
        {
            if (args.FailureInformation != null)
            {
                throw args.FailureInformation;
            }
            else
            {
                throw new Exception("Change password canceled due to new password validation failure.");
            }
        }
        SqlParameter[] p = new SqlParameter[3];
        p[0] = new SqlParameter("@applicationName", applicationName);
        p[1] = new SqlParameter("@username", username);
        p[2] = new SqlParameter("@password", EncodePassword(newPassword));

        bool retval = **dbConn.ExecuteSP("User_ChangePassword", p);**
        return retval;
    } //ChangePassword


    public override void Initialize(string name, NameValueCollection config)
    {
        if (config == null)
        {
            throw new ArgumentNullException("config");
        }

        ......

        ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

        if ((ConnectionStringSettings == null) || (ConnectionStringSettings.ConnectionString.Trim() == String.Empty))
        {
            throw new ProviderException("Connection string cannot be blank.");
        }

        connectionString = ConnectionStringSettings.ConnectionString;

        **dbConn = new DBConnect(connectionString);
        dbConn.ConnectToDB();**

        ......

} //Initialize

......

} // SGIMembershipProvider 

I have instantiated dbConn object within Initialize() event.

My problem is that how could i dispose off this object when object of SGIMembershipProvider is disposed off.

I know the GC will do this all for me, but I need to explicitly dispose off that object. Even I tried to override Finalize() but there is no such overridable method. I have also tried to create destructor for SGIMembershipProvider.

Can开发者_如何学Python anyone provide me solution.


From what I can see, MembershipProvider is not IDisposable (nor is ProviderBase), so we're really talking about garbage collection here, not disposal. You should be able to add your own finalizer (~SGIMembershipProvider() {}), but that should only talk to unmanaged objects - the other managed objects will also be collected, after all (and should handle their own unmanaged objects, if any - which is rare).


For this specific scenario, I would recommend directly creating your DB connection inside of each method you need it in, instead of storing a reference to it. Wrap it in a using statement and let the framework dispose it for you.

The reason I recommend this approach is that you aren't saving any resources by hanging on to that connection object. Connection pooling will handle reusing of existing open connections for you. Connection pooling works at the unmanaged code level. When you close/dispose of a managed Connection object, it doesn't necessarily close the physical unmanged connection, it simply returns the connection to the connection pool. The unmanaged code controlling the pool will then determine what to do with it (close it, keep it open for a bit, give it to another process that needs it). Likewise, when you create a managed connection, you are not necessarily creating a new connection from scratch, you may just be reusing an existing one.

I do think the framework needs to make this object disposable however. I can think of plenty of other situations in which I'd like to reuse something in the provider and dispose of it in the end.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜