Skip to content

factories

vijay@envivo edited this page May 21, 2026 · 12 revisions

Factories

When object construction becomes lengthy, a dedicated Factory class can help.
Implement your factory class by inheriting from IFactory<T>:

using Envivo.Fresnel.ModelTypes.Services;

public class CustomerFactory : IFactory<Customer> //👈
{
    /// <summary>
    /// Creates a Customer complete with its necessary properties
    /// </summary>
    /// <returns></returns>
    public Customer Create()
    {
        var customer = new Customer
        {
            Name = new(),
            Address = new(),
            Phone = new(),
            WebUser = new
            {
                State = UserState.New,
            },
            Account = new
            {
                OpenedOn = DateTime.Now,
                BillingAddress = new(),
            },
        };
        customer.WebUser.Customer = customer;
        customer.Account.Customer = customer;

        return customer;
    }
}

Whenever Fresnel needs to create an instance of a class, it will look inside the factory first. If a factory isn't found, the class' constructors are used instead.

Factory methods that accept parameters

Factory methods may also have parameters:

/// <summary>
/// Creates a Customer with the given name
/// </summary>
/// <param name="customerFirstName"></param>
/// <param name="customerLastName"></param>
/// <returns></returns>
public Customer CreateWithShoppingCart(string firstName, string lastName)
{
    var customer = this.Create();
    customer.Name.FirstName = firstName;
    customer.Name.LastName = lastName;
    customer.WebUser.ShoppingCart = new ShoppingCart();
    return customer;
}

These methods will appear in the main navigation panel:

When the option is clicked, you would be prompted for the values:

If a constructor accepts parameters that are dependencies, those will be injected automatically.

Clone this wiki locally