Skip to content

amileszko/type-extensions-poco-builder

Repository files navigation

POCO Builder

CI NuGet
Quality Gate Status Coverage Security Rating Maintainability Rating Reliability Rating

What is POCO Builder?

POCO builder is a light-weight library that creates POCO (Plain Old CLR Object) type at runtime from any compile time defined type. All properies defined in POCO type has automatically created getters and setters and can be extended with attributes just like the type itself.

How do I get started?

Just install NuGet package and use PocoTypeBuilder class to create new POCO type. For example:

//Define test attribute to extend POCO type and its property
public class TestAttribute : Attribute
{
}

//Create POCO type builder
var pocoTypeBuilder = new PocoTypeBuilder("TestClass");

//Extend build POCO type with attribute and then create new property and extend it with attribute
pocoTypeBuilder
    .AddAttribute<TestAttribute>()
    .Property("Property",
        typeof(string),
        propertyBuilder => propertyBuilder.AddAttribute<TestAttribute>());
        
/*
Build POCO type.
Created POCO type class looks like this:

[TestAttribute]
public class TestClass
{
   [TestAttribute]
   public string Property { get; set; }
}
*/
var pocoType = pocoTypeBuilder.Build();

//Access POCO type property through reflection.
var propertyInfo = pocoType.GetRuntimeProperty("Property");

You can also use generic PocoTypeBuilder class to use strongly typed property selector:

//Create POCO type builder for test class
var pocoTypeBuilder = new PocoTypeBuilder<TestClass>();

//Extend build POCO type and its property with attribute
pocoTypeBuilder
    .AddAttribute<TestAttribute>()
    .Property(type => type.Property,
        propertyBuilder => propertyBuilder.AddAttribute<TestAttribute>());

You can check out more examples in test project.

Contribution

Welcome to join in and feel free to contribute by creating an Issue or Pull Request.

License

The project is under MIT license.