Try our conversational search powered by Generative AI!

Kristoffer Lindén
Dec 13, 2021
  1313
(1 votes)

How to simplify initialization for your custom plugin

When your are creating a custom plugin you might want to initialize your plugin on startup. You could of course add everything you need in the Optimizely Startup.cs class but is is much nicer to have the user just adding one row of code using an extension method.

Your extension could look something like this:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddMyPlugin(this IServiceCollection services, string connectionString)
    { 
        services.AddDbContext<MyDbContext>(x => x.UseSqlServer(connectionString))
            .AddScoped<Microsoft.EntityFrameworkCore.DbContext, MyDbContext>()
            .AddSingleton<IMyService1, MyService>()
            .AddSingleton<IMyService2, MyService2>();      

        return services;
    }
}

And the only thing you need to add in Startup.cs is this:

services.AddMyPlugin(_configuration.GetConnectionString("EpiserverDB"));

I had som static content that generated 404 so I also had to create an extension to handle static content.

public static IApplicationBuilder UseMyPluginStaticContent(this IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, "modules", "MyPlugin", "ClientResources")),
        RequestPath = "/modules/MyPlugin/ClientResources"
    });

    return app;
}

and the add this row in the Startup.cs Configure method:

app.UseMyPluginStaticContent(env);

This is an easy way to create advanced initialization but the user only needs to add two rows of code that clearly points out that they are use by My Plugin.

Dec 13, 2021

Comments

Please login to comment.
Latest blogs
A day in the life of an Optimizely Developer - Enabling Opti ID within your application

Hello and welcome to another instalment of A Day In The Life Of An Optimizely developer, in this blog post I will provide details on Optimizely's...

Graham Carr | May 9, 2024

How to add a custom property in Optimizely Graph

In the Optimizely CMS content can be synchronized to the Optimizely Graph service for it then to be exposed by the GraphQL API. In some cases, you...

Ynze | May 9, 2024 | Syndicated blog

New Security Improvement released for Optimizely CMS 11

A new security improvement has been released for Optimizely CMS 11. You should update now!

Tomas Hensrud Gulla | May 7, 2024 | Syndicated blog

Azure AI Language – Key Phrase Extraction in Optimizely CMS

In this article, I demonstrate how the key phrase extraction feature, offered by the Azure AI Language service, can be used to generate a list of k...

Anil Patel | May 7, 2024 | Syndicated blog