Skip to content
This repository has been archived by the owner on Jun 14, 2021. It is now read-only.

Quickstart

Jonathan edited this page Dec 18, 2018 · 3 revisions

For .NET Core Console Application

  1. Add the OmniXaml.Services package to it
  2. Insert this code:
using System;
using System.Collections.Generic;
using System.Reflection;
using OmniXaml.Attributes;
using OmniXaml.Services;

[assembly: XmlnsDefinition("root", "Sample")]   // We define a namespace named "root" that will map to the Sample namespace
namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            IList<Assembly> assemblies = new List<Assembly> { Assembly.GetEntryAssembly() };
            var constructionResult = new XamlLoader(assemblies).Load(@"<MyObject xmlns=""root"" Property=""Hello!"" />");
            var instance = constructionResult.Instance;

            Console.WriteLine(instance);
        }
    }

    public class MyObject
    {
        public override string ToString()
        {
            return $"Hola, soy un {GetType().Name} y mi propiedad dice: {Property}";
        }

        public string Property { get; set; }
    }
}
  1. Run it!

What are we doing here?

  • First, we are create a list of assemblies in which our model is defined (these are our Reference Assemblies). In our sample, the Reference Assemblies will be a list with only one element: our Entry Assembly, that is the assembly that contains our model.

  • We create a XamlLoader using our Reference Assemblies. This way, the XamlLoader knows where to look when inflating the types in the XAML. It also scans for specific attributes like ContentProperty or XmlnsDefinition that provide metadata about the model.

  • In the very same line, we invoke the Load method with the XAML itself. Notice that this XAML is very simple:

    <MyObject xmlns="root" Property="Hello!" />

    This XAML starts with a MyObject element, followed by a namespace prefix declaration and the assignment of a property. The xmnls="root" part is the more mystic part. It's used to define the 'default' namespace prefix that will be used to locate the types. With a prefix we know the namespace, and with the namespace we know where to look for a type. In this case we put "root" because it's the namespace we defined above with [assembly: XmlnsDefinition("root", "Sample")]

  • After the Load, the loader will return a ConstructionResult object. Inside this object, we will find the Instance property that is the object that has been loaded.

For now, it's enough. More to come soon!

Clone this wiki locally