Dependency injection

Jerrycurl does not support dependency injection out of the box, but allows you to easily set it up using your favorite DI library.

Basic setup

You can set up DI by adding a few services to your container, and in the examples below we will do so using the great Simple Injector.

First create an empty container.

Container container = new Container();

Make sure it can resolve IServiceProvider which is the basis for Jerrycurl's DI interface.

container.Register<IServiceProvider>(() => container);

Add a domain and a custom DbSettings instance with the connection string to use.

container.Register<MyDomain>();
container.
RegisterSingleton(() => new DbSettings()
{
    ConnectionString = 
"..."// or get from someplace nice
});

Add AccessorContext and use the special initializer feature to assign this to every accessor.

container.Register<AccessorContext>();
container.
RegisterInitializer<Accessor>(a =>
{
    a.Context = container.
GetInstance<AccessorContext>();
});

Add the accessors you want to use.

container.Register<SomeAccessor>();
container.
Register<OtherAccessor>();

And that's it! Now let's take a look at how we can utilize

Domain services

The most common scenario for using services in your domain is to inject configuration.

class BlogDomain : IDomain
{
    
private readonly DbSettings settings;

    
public BlogDomain(DbSettings settings)
    {
        
this.settings = settings;
    }

    
public void Configure(DomainOptions options)
    {
        options.
UseSqlServer(this.settings.ConnectionString);
    }
}

Razor services

Adding the above code also gives the ability to use the @inject directive to gain access to context-based values in your SQL code.

@result Blog
@inject UserContext ctx

SELECT  @R.Star()
FROM    @R.Tbl()
WHERE   @R.Col(m => m.UserId) = @ctx.UserId