Extend a Type

Lynicon allows modules and client code to extend most existing content container types.  CoreDb achieves this by scanning the loaded assemblies when the application initialises to find all the types inheriting from base types registered with it.  It then dynamically creates a type which inherits from the base type and includes all the fields from all the types it has found.  It marks this type as having any interfaces associated with the subtypes it has found which are appropriate.

The Data API will then return values of the dynamic type it has created cast to the base container type.  To access the extended fields, you can cast this to the appropriate interface.  To illustrate this, the steps required to extend the User type, a common requirement for client code, are shown below.

Extending the User type

The steps are as follow:

  1. Add the relevant fields to the database record User e.g. Postcode.
  2. Declare an interface (e.g. INewUser) containing any number of the base type fields plus Postcode.

    public interface INewUser
    {
    	string Email { get; set; }
    	string Postcode { get; set; }
    }
  3. Declare a class (e.g. NewUser) which inherits from User in the client code and attach it to NewUser:

    public class NewUser : User, INewUser
    {
    	public string Postcode { get; set; }
    }

     

  4. Configure the new type extension in Startup.cs:

    services.AddLynicon(options =>
        options.UseConfiguration(Configuration.GetSection("Lynicon:Core"))
             .UseModule<CoreModule>()
             .UseModule<Storeless>(Configuration.GetSection("Lynicon:Storeless:Cache"))
             .UseTypeSetup(col =>
             {
                 col.System.Extender.AddExtensionRule(typeof(User), typeof(IUserAccessRestriction));
             })
        )
     .AddLyniconIdentity();

    The line that should be added within .UseTypeSetup is col.System.Extender.AddExtensionRule(<original type>, <extension interface>);

    Other code shown above is just to provide an example context.

  5. All Users retrieved from calls to the Data API will now contain the Postcode field in the underlying type, which will also implement INewUser.  To get the postcode of the current user, do this:

    var postcode = ((INewUser)LyniconSecurityManager.Current.User).Postcode;
  6. If you extend the User record like this, the User Management screen will show the new field which you can now use as normal.