Getting Started with H.Necessaire: IoC, Dependency Groups and Wireup
The dependency registry, ImADependency and ImADependencyGroup, the wireup API and ASP.NET Core integration.
Applies to H.Necessaire 4.0.5.
Everything in H.Necessaire hangs off one small idea: a dependency registry. You register factories, the registry builds things lazily, and dependency groups let each package register its own pieces in one call. This article covers the registry, the two interfaces you implement to take part, and how the ASP.NET Core integration wires it all into a web app.
Install
dotnet add package H.NecessaireThe registry
ImADependencyRegistry deps = IoC.NewDependencyRegistry();
// Singleton: the factory runs once, on first Get
deps.Register<IMyService>(() => new MyService());
// Transient: a new instance on every Get
deps.RegisterAlwaysNew<IMyWorker>(() => new MyWorker());
IMyService service = deps.Get<IMyService>();
bool known = deps.HasTypeRegistered<IMyService>();
deps.Unregister<IMyService>();Registration returns the registry, so calls chain. A few behaviours worth knowing, all visible in the source:
Registeris lazy and singleton. The factory runs the first time someone callsGet;RegisterAlwaysNewruns it every time.- Registering a type again replaces the earlier registration.
Getreturnsnullfor an unknown type (it doesn't throw). If the type is generic and only the open generic definition is registered, that registration is used.- There are overloads that receive the requested
Type, which is how a single factory can serve a generic type.
ImADependency: getting your own dependencies
Constructors with long parameter lists are replaced by one method. If your class implements ImADependency, the registry calls ReferDependencies right after it builds the instance:
public class OrderService : ImADependency
{
ImALogger logger;
ImAStorageService<Guid, Order> storage;
public void ReferDependencies(ImADependencyProvider dependencyProvider)
{
logger = dependencyProvider.GetLogger<OrderService>();
storage = dependencyProvider.Get<ImAStorageService<Guid, Order>>();
}
}Because resolution is lazy, registration order doesn't matter: dependencies are looked up when the instance is first created, not when it is registered.
ImADependencyGroup: registering a module in one call
public class OrdersDependencyGroup : ImADependencyGroup
{
public void RegisterDependencies(ImADependencyRegistry dependencyRegistry)
{
dependencyRegistry
.Register<OrderService>(() => new OrderService())
.Register<IOrderValidator>(() => new OrderValidator());
}
}
deps.Register<OrdersDependencyGroup>(() => new OrdersDependencyGroup());The registry runs RegisterDependencies at the moment you register the group, and it runs it only once per group type, so two modules can safely both register a shared group. Groups must be registered with Register; RegisterAlwaysNew throws for them.
H.Necessaire's own pieces are groups. The core one is HNecessaireDependencyGroup, which brings in logging, caching, sync, versioning, cryptography, cancellation management, TOTP and the QD action pipeline:
var deps = IoC.NewDependencyRegistry();
deps.Register<HNecessaireDependencyGroup>(() => new HNecessaireDependencyGroup());
ImALogger log = deps.GetLogger<Program>();
await log.LogInfo("Hello from H.Necessaire");Adding H.Necessaire.Runtime gives you RuntimeDependencyGroup, a superset that registers the core group plus HTTP, security, sync, logging, analytics, use cases, QD actions and daemons:
deps.Register<RuntimeDependencyGroup>(() => new RuntimeDependencyGroup());The wireup API
H.Necessaire.Runtime also defines ImAnApiWireup, a small fluent wrapper over a registry. With(...) lets you register anything, and WithEverything() registers the runtime group:
public interface ImAnApiWireup
{
ImADependencyRegistry DependencyRegistry { get; }
ImAnApiWireup With(Action<ImADependencyRegistry> registry);
ImAnApiWireup WithEverything();
}Derive from ApiWireupBase to get the plumbing and override WithEverything() to add your app's own groups.
ASP.NET Core
Install
dotnet add package H.Necessaire.Runtime.Integration.AspNetCoreThe integration gives you three calls. This is the shape used by the repository's own sample app:
ImADependencyRegistry registry = IoC.NewDependencyRegistry();
registry.Register<RuntimeConfig>(() => new RuntimeConfig
{
Values = new[] { "App".ConfigWith("Name".ConfigWith("My App")) }
});
// ...register your own dependency groups here...
var builder = WebApplication.CreateBuilder(args).WithHNecessaire(registry);
var app = builder.Build().BindToHNecessaireAspNetRuntime(registry);
app.ConfigureHNecessaireAspNetRuntime(app.Environment);
app.Run();What each call does:
WithHNecessaire(registry)adds the HTTP context accessor and antiforgery, then copies every registration in the registry into the ASP.NET service collection (singletons as singletons, always-new types as transients, and anything implementingIHostedServiceas a hosted service). It also replaces the default logging providers with H.Necessaire's logger. It adds MVC controllers and a default CORS policy that allows any origin, header and method, so tighten that for production.BindToHNecessaireAspNetRuntime(registry)connects the two worlds after the host is built: it makesImAUseCaseContextProviderHTTP-context aware and ties the cancellation manager to the application's stopping token.ConfigureHNecessaireAspNetRuntime(env)adds the request pipeline: request buffering, the exception handler middleware, HTTPS redirection (skipped when the environment is namedLocal), routing, antiforgery, CORS and controller endpoints.
Register everything before you call WithHNecessaire. It snapshots the registry at that moment, so groups registered afterwards won't appear in the ASP.NET service collection.
Other hosts
For a plain .NET host, Integration.DotNet offers WithHNecessaireDotNetRuntimeIntegration(configuration) on the registry. It registers the runtime group (if absent), an ImAConfigProvider over IConfiguration, the ILogger provider, and a use case context provider. ILoggingBuilder.AddHNecessaireLogging(...) routes Microsoft.Extensions.Logging output into H.Necessaire's logging pipeline.
Next
Configuration is the next piece: see the runtime configuration reference.