271
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Scrutor
library for that. This approach is convenient when you have dozens
of types that need to be
registered in your IoC container.
Additional resources
•
Matthew King. Registering services with Scrutor
https://www.mking.net/blog/registering-services-with-scrutor
•
Kristian Hellang. Scrutor.
GitHub repo.
https://github.com/khellang/Scrutor
Use Autofac as an IoC container
You can also use additional IoC containers and plug them into the ASP.NET Core pipeline, as in the
ordering microservice in eShopOnContainers, which uses
Autofac
. When using Autofac you typically
register the types
via modules, which allow you to split the registration types between multiple files
depending on where your types are, just as you could have the application types distributed across
multiple class libraries.
For example, the following is the
Autofac application module
for the
Ordering.API Web API
project
with the types you will want to inject.
public
class
ApplicationModule : Autofac.
Module
{
public
string
QueriesConnectionString {
get
; }
public
ApplicationModule
(
string
qconstr)
{
QueriesConnectionString = qconstr;
}
protected
override
void
Load
(ContainerBuilder builder)
{
builder.
Register
(c =>
new
OrderQueries
(QueriesConnectionString))
.
As
()
.
InstancePerLifetimeScope
();
builder.
RegisterType
()
.
As
()
.
InstancePerLifetimeScope
();
builder.
RegisterType
()
.
As
()
.
InstancePerLifetimeScope
();
builder.
RegisterType
()
.
As
()
.
InstancePerLifetimeScope
();
}
}
Autofac also has a feature to
scan assemblies and register types by name conventions
.
The registration process and concepts are very similar to the way you can register types with the built-
in ASP.NET Core IoC container, but the syntax when using Autofac is a bit different.
In the example code, the abstraction IOrderRepository is registered along with the implementation
class OrderRepository. This means that whenever a constructor is declaring a dependency through the
272
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
IOrderRepository
abstraction or interface, the IoC container will inject an instance of the
OrderRepository class.
The instance scope type determines how an instance is shared between requests for the same service
or dependency. When a request is
made for a dependency, the IoC container can return the following:
•
A single instance per lifetime scope (referred to in the ASP.NET Core IoC container as
scoped
).
•
A new instance per dependency (referred to in the ASP.NET Core IoC container as
transient
).
•
A single instance shared across all objects using the IoC container (referred to in the ASP.NET
Core IoC container as
singleton
).
Dostları ilə paylaş: