开发者

ASP.NET: Implementing Init and Dispose methods

开发者 https://www.devze.com 2023-02-24 17:09 出处:网络
Can an ASP.NET web application have only one Init and one Dispose method or can I implement these per class for those which I want to associate such methods?

Can an ASP.NET web application have only one Init and one Dispose method or can I implement these per class for those which I want to associate such methods?

More specifically I have Customer component and a CustomerRecord classes and would like to implement Init and Dispose methods in both of them.

What is the proper way to do this?

Requirement:

I wan开发者_StackOverflow社区t to have independent Init and Dispose methods for each aforementioned class.


For classes that should be disposable, by exposing a public Dispose method, the IDispsable interface must be implemented for 'disposability' to be effective out of the scope of explicit user disposal. This has been covered many times in many places, including here, for example:

public class Customer : IDisposable
{
    public void Dispose()
    {
        Dispose(true);
        GC.SupressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            //dispose of managed resources
        }
        //dispose of unmanaged resources
    }

    ~Customer()
    {
        Dispose(false);
    }
}

Note that the destructor (the method starting with the tilde ~) may not be necessary, but read the details from the answer I linked above for clarity on the situation of what and why - this just answers your question directly.

As for an Init method, are you referring to a constructor?

If so, then look at the destructor in the above example; a constructor (or initialiser) can be defined in the same way minus the tilde and, generally, plus an explicit access modifier (public, private, et cetera), for example:

public class Customer
{
    public Customer()
    {

    }
}


You can create a base class with the Init and Dispose method as you wish and then make the other classes to inherit from it. For example:

public class BaseClass
{
    public void Init()
    {
        //Some code
    }

    public void Dispose()
    {
        //Some code
    }
}

public class Customer : BaseClass
{
    //Some code
}

That might help you.

0

精彩评论

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

关注公众号