-
Notifications
You must be signed in to change notification settings - Fork 1
Dependency Injection
Telefrag exposes Dependency Injection containers for use by consumers and producers in the Telefrag ecosystem.
Telefrag uses the Unity DI container because it allows services to be modified and added at runtime; unlike the Microsoft.DependencyInjection system which builds a ServiceCollection into a ServiceProvider which is a one-time process and requires a re-instantiation of all services in order for bindings to be added (such as when someone loads a module/plugin after startup), among many other limitations.
Telefrag's internal DI (which is based on UnityContainer) coexists with Microsoft's DI environment if using Telefrag in an ASP.NET environment:
- Telefrag contains extension methods such as
UseTelefrag()andAddTelefrag()to hook into the ASP.NET DI and middleware pipeline. - ASP.NET's DI services are registered into Telefrag's DI containers.
- The root container is
App.Services-- anything registered here will be resolvable anywhere (unless overriden at a lower level). Children of this container are:- The context root container (
App.ContextServices) - The sender root container (
App.SenderServices)
- The context root container (
And then each sender (bot, client, etc.) and context will have a service container that is a child of the respective root container. Senders that are children of other senders (a Bot in a Fleet) have their service containers nested respectively.
Examples of services that would be registered to the context root container would be services that are scoped to each event or action, web request, telegram message, etc, such as a database context instance.
Longer-term or more broadly used services would typically be registered at the Application level, Sender Root level, or directly on a Bot or Client if the service only applied to that sender.
See the Unity Documentation for information on resolving and registering services. Typically you'd access service containers at:
-
Bot.Services,Client.Services, etc... -- pretty much anyIServiceNode.Services -
Context.Services-- context-specific services
These containers all roll up, so if a services isn't found registered on the Bot, the Sender Root is checked, then the App Root, and then finally null would be returned.
var mailer = Bot.Services.Resolve<SmtpGateway>();Only interface mappings need to be registered with Unity. Concrete types can be resolved without registration and Unity will attempt to construct your class using a constructor. If you have complicated creation needs, register a factory method with Services.RegisterFactory(). You can also register existing instances with Services.RegisterInstance() in the event a service object was created outside DI.
App.Services.RegisterType<ISpellChecker, HipHopSpellChecker>();
App.Services.RegisterType<ILateNight, ConanLateNight>();