Search This Blog

Friday, November 2, 2012

System.Type of DC interfaces vs registered business entities

If you are using Domain Components (DC), you may be already aware of the fact that XAF generates real business entities from registered DC interfaces at runtime. If you have a code that checks types of the current object (e.g., you want to do something only if the current object is of YourBusinessEntityType), you should take this important fact into account, otherwise it may lead to an error, which is quite easy to diagnose, though. A good example of this can be found in this Support Center ticket (which actually forced me to blog about this):

using DevExpress.ExpressApp.DC;
using DevExpress.ExpressApp.Xpo;
...
private void checkType_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            foreach (object current in View.SelectedObjects)
            {
                /* This is wrong, because real types are generated at runtime based on registered DCs.
if (current.GetType() == typeof(DomainComponent1)) 
                */
                //The next three variants are good to go.
                //if (typeof(DomainComponent1).IsAssignableFrom(current.GetType()))
                //if (current.GetType() == ((IDCEntityStore)XafTypesInfo.PersistentEntityStore).GetGeneratedEntityType(typeof(DomainComponent1)))
                if (current.GetType() == XpoTypesInfoHelper.GetXpoTypeInfoSource().GetGeneratedEntityType(typeof(DomainComponent1)))
                    DoSomethingUseful();
            }
        }
...

As you can see, DC provides you with a method that returns the generated runtime type. Also, the type of the generated entity supports or implements DC interfaces used to form this entity, so you can use the System.Type.IsAssignableFrom method here.
I hope you find this information helpful.

No comments:

Post a Comment