foreach (
var
item
in message.
OrderItems
)
{
order.
AddOrderItem
(item.
ProductId
, item.
ProductName
, item.
UnitPrice
,
item.
Discount
, item.
PictureUrl
, item.
Units
);
}
_logger.
LogInformation
(
"----- Creating Order - Order: {@Order}"
, order);
_orderRepository.
Add
(order);
return await _orderRepository.
UnitOfWork
.
SaveEntitiesAsync
(cancellationToken);
}
}
The class uses the injected repositories to execute the transaction and persist the state changes. It
does not matter whether that class is a command handler, an ASP.NET Core Web API controller
method, or a
DDD Application Service
. It is ultimately a simple class that uses repositories, domain
entities, and other application coordination in a fashion similar to a command handler. Dependency
Injection works the same way for all the mentioned classes, as in the example using DI based on the
constructor.
Register the dependency implementation types and interfaces or abstractions Before you use the objects injected through constructors, you need to know where to register the
interfaces and classes that produce the objects injected into your application classes through DI. (Like
DI based on the constructor, as shown previously.)
Use the built-in IoC container provided by ASP.NET Core When you use the built-in IoC container provided by ASP.NET Core, you register the types you want
to inject in the
Program.cs file, as in the following code:
// Register out-of-the-box framework services.
builder.
Services
.
AddDbContext
(c =>
c.
UseSqlServer
(Configuration[
"ConnectionString"
]),
ServiceLifetime.
Scoped
);
builder.
Services
.
AddMvc
();
// Register custom application dependencies.
builder.
Services
.
AddScoped
();
The most common pattern when registering types in an IoC container is to register a pair of types
—
an
interface and its related implementation class. Then when you request an object from the IoC
container through any constructor, you request an object of a certain type of interface. For instance, in
the previous example, the last line states that when any of your constructors have a dependency on
IMyCustomRepository (interface or abstraction), the IoC container will inject an instance of the
MyCustomSQLServerRepository implementation class.