开发者

How to do lazy loading part of a middle layer business object?

I want to build a business object such as an employee class, but I know that 80% of the properties will barely get used. So I wanted to know how I can create the object with the i开发者_开发知识库mportant properties in the constructor and lazy load the ones that are barley used when they are needed (if at all).

I am using asp.net with c#.


If you are working with pure business class, use the System.Lazy class.

This class (.net v4 minimum) allow you to defer the filling of a container to the first call, in a thread safe way :

public class TestLazy
{
    private Lazy<MyClass> m_lazyObj;


    public MyClass MyClassInstance
    {
        get { return m_lazyObj.Value; }
    }


    public TestLazy()
    {
        m_lazyObj = new Lazy<string>(() => DoTheHeavyJobToGetMyClassInstance);
    }
}

If you are using an ORM, as other said in the post, lazy loading will probably be provided by the ORM engine.

[Edit]: added a code sample


The most obvious way of doing it is,

public Constructor(Object importantPropertyValue)
{
    this.ImportantProperty = importantPropertyValue;
}

public Object ImportantProperty{get; private set;}


private Object _unimportantProperty;

public Object UnimportantProperty
{
    Get
    {
        if(_unimportantProperty == null)
        {
            _unimportantProperty = FetchUnimportantPropertyValue() // how ever you load it
        }

        return _unimportantProperty;
    }


Assuming you are talking about lazy loading from a database here then you could build your domain objects using Entity Framework 4.0, and get lazy loading for free.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜