简体   繁体   中英

Elegant Solution for Initializing One Class (but not another)

I have an app that supports two data access layers: db4o and RavenDB. The logic classes make calls like this to get a concrete data class:

return DataAccessFactory.GetDataInterface<IApplicationData>().GetAll();

Here is the method in DataAccessFactory that returns the correct ApplicationData (db4o or RavenDB) concrete class:

public static T GetDataInterface<T>() where T : class
{
    T theObject = // Code here to get the object. Not relevant to this question.

    // Begin HACK

    DataAccessLayerBase theObjectAsRavenDalBase = theObject as DataAccessLayerBase;

    if (theObjectAsRavenDalBase != null)
    {
        theObjectAsRavenDalBase.SetAsInitialDalInstanceAndCreateSession();
    }

    // End HACK

    return theObject as T;
}

The hack that I've implemented is casting to RavenDB's version of DataAccessLayerBase and that statement. 语句。 If the concrete class happens to be a RavenDB class, then I need to call a method on it. (The DataAccessLayerBase, shown here, is in the RavenDb namespace. db4o also his its own DataAccessLayerBase.)

One way to fix this would be to have each DataAccessLayerBase implement a common method, like Initialize(). The db4o Initialize() method would do nothing, and the RavenDB Initialize() method would perform the necessary logic. Then this method could simply call Initialize() and not care which concrete class it was.

Is there a better design than this? I think the fix that I just described is decent enough, but I can't help but think I'm missing something. I'm looking for a better, more elegant way to solve this. One drawback with my proposed approach is that other data access layers must then implement Initialize() even though I only needed it for RavenDB.

Note: I can't just have the concrete classes do this initialization when they're created, because it should only happen when a call is made to DataAccessFactory.GetDataInterface<>().

One other solution would be to add a type property on an interface implemented by your DataAccess classes. You could then check the type to know if you need to call the SetAsInitialDalInstanceAndCreateSession method. I think the Initialize method you describe above is a good solution too though

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM