Jump to content

Dependency Injection


rhodges

Recommended Posts

rhodges

Is there a way in the server api to register your own class/interface to be available for dependency injection?

Link to comment
Share on other sites

There is no way for plugins to register singleton instances. But the dependency injection will automatically instantiate your classes via constructor injection and when calling Emby SDK Reference: IApplicationHost.Resolve<T>(). This doesn't require registration, you just need to make sure that a class has just a single public constructor and all constructor parameters can be resolved by the injector as well (either registered Emby singletons by specifying the interface or concrete classes to which the above applies).

This is quite handy, but doesn't allow you to access a central and single instance for your plugin. Older plugins were exposing themselves via a static property. This is a disregarded pattern though (for multiple resaons), and hence I appreciate your question, which is essentially about avoid this (simple but problematic) pattern.

There's a better way to get at your pugin instance:

private MyPlugin GetPluginInstance(IApplicationHost applicationHost)
{
    var plugin = applicationHost.Plugins.OfType<MyPlugin>().FirstOrDefault();
    if (plugin == null)
    {
        throw new Exception("The plugin is not loaded");
    }

    return plugin;
}

 

  • Like 1
Link to comment
Share on other sites

Dependency injection is a quite useful pattern, but it also has some drawbacks in certain cases like for example it can lead to constructor bloat, or if  you have a lot of singleton objects which you cannot register (see above) from a plugin.

We have another patterrn used in newer development, which complements (but doesn't replace) DI. 
It is about using a common base class for all the classes in your plugin codebase (except the plugin itself). The base class for your base class is Emby SDK Reference: CommonBaseCore. It provides a number of useful methods for logging, localization and service acquisition - via Emby SDK Reference: CommonBaseCore.GetService<T>().
The latter is equivalent to Emby SDK Reference: IApplicationHost.Resolve<T>(), which you can override to return your own "registered" singleton objects and otherwise fallback to the base implementation.

To use this, you need to create your base class, e.g. "CommonBase", deriving from "CommonBaseCore" and you also need to create an implementation of Emby SDK Reference: IServiceRoot for adding your custom mechanism for resolving.
Then you can derive your classes from that base class.

Let me know when you got any more questions about it.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...