Simple Injector Property Injection - ninject

How do you perform property injection with Simple Injector.
The with Ninject you do is as per bellow:
[Inject]
public IUnitOfWork UnitOfWork { get; set; }
How can I do the equivalent to this with Simple Injector. I tried finding a solution online but had no luck.
Why do I want to use Property Injection?
I want to use property injection to set up unit of work in my base controller so that it will create a new unit of work OnActionExecuting and commit the changes OnResultExecuted. It also means I don't have to pass in the UoW with each new controller I create through the constructor.

Another option is to use the RegisterInitializer method:
container.RegisterInitializer<BaseControllerType>(controller =>
{
controller.UnitOfWork = container.GetInstance<IUnitOfWork>();
}
It keeps all configuration in your composition root and does not pollute your code base with all kinds of attributes.
Update: (as promised)
While this is a direct answer to your question I have to provide you with a better option, because the usage of a base class for this is a IMO not the correct design, for multiple reasons.
Abstract classes can become real PITA classes as they tend to grow towards a god class which has all kinds of cross cutting concerns
An abstract class, especially when used with property injection, hides the needed dependencies.
With focus on point 2. When you want to unit test a controller which inherits from the base controller, you have no way of knowing that this controller is dependent on IUnitOfWork. This you could solve by using constructor injection instead of property injection:
protected abstract class BaseController : Controller
{
protected readonly IUnitOfWork uoW;
protected BaseController (IUnitOfWork uoW)
{
this.uoW = uoW;
}
}
public class SomeController : BaseController
{
public SomeController(IUnitOfWork uoW) : base(uoW) { }
}
While this solves point 2, point 1 is still lurking. The main reason you're wanting this, as you say, is because you do not want to commit your changes in every Action method. Changes must just be saved by the context when the request is done. And thinking about design in this way is a good thing, because Saving changes is, or can be seen as a cross cutting concern and the way you're implementing this is more or less known as AOP.
If it's comes to AOP, especially if you're working with atomic actions in the action methods of your controllers, there is a far better, more SOLID and more flexible design possible which deals with this very nicely.
I'm referring to the Command/Handler pattern which is described in great detail here (also read this for the query part of your application).
With this patterns you don't inject a generic IUnitOfWork abstraction, but inject the specific needed ICommandHandler<TCommand> abstractions.
The action methods would fire the responsible commandhandler for this specific action. All commandhandlers can simple be decorated by a single open-generic SaveChangesCommandHandlerDecorator, 'ValidationDecorator', 'CheckPermissionsDecorator', etc...
A quick example:
public class MoveCustomerCommand
{
public int CustomerId;
public Address NewAddress;
}
public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
// retrieve customer from database
// change address
}
}
public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decoratee;
private readonly DbContext db;
public SaveChangesCommandHandlerDecorator(
ICommandHandler<TCommand> decoratee, DbContext db)
{
this.decoratee = decoratee;
this.db = db;
}
public void Handle(TCommand command)
{
this.decoratee.Handle(command);
this.db.SaveChanges();
}
}
// Register as
container.Register(typeof(ICommandHandler<>), new []{Assembly.GetExecutingAssembly() });
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(SaveChangesCommandHandlerDecorator<>));
// And use in controller as
public ActionResult MoveCustomer(int customerId, Address address)
{
var command = new MoveCustomerCommand
{ CustomerId = customerId, Address = address };
this.commandHandler.Handle(command);
return View(new ResultModel());
}
This keeps your controllers clean and let it do what it must do, namely be the layer between the business logic (the commandhandler implementation in this case) and the view.

Need to create the following:
First create the attribute class
[System.AttributeUsage(System.AttributeTargets.Property]
public class Inject : Attribute
{
}
Then create a custom property behavior
class PropertySelectionBehavior<TAttribute> : IPropertySelectionBehavior
where TAttribute : Attribute
{
public bool SelectProperty(Type type, PropertyInfo prop)
{
return prop.GetCustomAttributes(typeof(TAttribute)).Any();
}
}
Finally tell the container to use custom behavior
container.Options.PropertySelectionBehavior = new PropertySelectionBehavior<Inject>();
All that is left to do is decorate the property with the attribute
[Inject]
public IUnitOfWork UnitOfWork { get; set; }

Related

Passing DI object to constructor of new class

So, in Razor Pages I know how I can use Dependency Injection to inject my DbContext (for example) in the constructor to access it in the whole class by creating a global private readonly variable.
However, let's say I have a DbManager class that makes all the calls to the DB (to avoid making them from every Razor Page in the application), then I have to pass the context to that class, even though I'm using (at least to my knowledge) dependency injection there as well.
Shouldn't it be able to find it without actually passing it to the constructor, and isn't that the whole point of dependency injection, or am I missing something?
What is the best practice here? Just feels wrong to pass the context as a parameter! I suspect I'm doing something wrong... Am I?
public class IndexModel : PageModel
{
private readonly AppDbContext _context;
public IndexModel(AppDbContext context)
{
_context = context;
}
public void OnGet()
{
var result = new DbManager(_context).GetStuffFromDb(); // Feels weird to pass the context as a parameter here!
}
}
If you are not making any explicit reference calls to the context within IndexModel then only inject the DbManager.
private readonly IDbManager manager;
public IndexModel(IDbManager manager) {
this.manager = manager;
}
public void OnGet() {
manager.GetStuffFromDb();
//...
}
The context will be injected into the manager when being resolved, provided it (the context) was also registered in the composition root
//...
builder.Services.AddScoped<IDbManager, DbManager>();
builder.Services.AddDbContext<AppDbContext>(....);
//...
Reference Explicit Dependencies Principle

NSubstitute for the EF's Core DbContext - how to use it?

I'm trying to create the unit test for a class which uses my EF Core DbContext:
public class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
public DbSet<SomeTable> SomeTables { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
...
}
}
the class which is consuming that context is simple:
public class MyClass
{
public MyClass(MyContext db)
{
}
}
so, when I try to create
var fakeContext = Substitute.For<MyContext>();
which ends with the error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: MyContext.
Could not find a parameterless constructor.
which is being raised by base(options) constructor. So, the net approach was to extend the code:
var dbContextOptions = Substitute.For<DbContextOptions<MyContext>>();
dbContextOptions.ContextType.Returns(typeof(MyContext));
var dbContextOptionsExtension = Substitute.For<IEnumerable<IDbContextOptionsExtension>>();
dbContextOptions.Extensions.Returns(dbContextOptionsExtension);
var myFakeContext = Substitute.For<MyContext>(dbContextOptions);
but it generates more and errors. So, how to fix it ?
You haven't elaborated on the additional errors so I can't provide a specific answer, however trying to mock a DbContext properly is difficult. IMO there are two options.
1) Use the Microsoft in-memory provider.
2) If you want to use a mocked DbContext using NSubstitute, use a pre-existing library that does the mocking for you. There are a few around such as EntityFrameworkCore.Testing.NSubstitute (disclaimer - I am the author).
The in-memory provider is not a complete implementation, it can't do relational operations and there are a swag of LINQ operations it doesn't support, so depending on your use cases the latter may be a better solution.
If you have a specific error/use case in mind pop it up and I may be able to provide a better answer.
Ok, I've used the InMemory provider:
var options = new DbContextOptionsBuilder<AgreementContext>()
.UseInMemoryDatabase("fakeDb")
.Options;
var agreementContext = Substitute.For<MyContext>(options);

StructureMap - Inject Conditional Class

I have 1 interface named IProcessor having multiple implementations like ABCProcessor, PQRProcessor.
I want to make use of specific processor based on external parameters. How can I achive the same using StructureMap.
I am looking at named instances for the same.
You could use a factory pattern:
public interface IProcessorFactory
{
IProcessor Create(int dropDownValue);
}
public class ProcessorFactory : IProcessorFactory
{
private readonly IContainer _container;
public ProcessorFactory(IContainer container)
{
_container = container;
}
public IProcessor Create()
{
if(//your condition)
return _container.GetInstance<ABCProcessor>();
_container.GetInstance<PQRProcessor>();
}
}
(or simply inject the required dependencies instead of the container)
and then simply
private readonly IProcessorFactory _processorFactory;
public MvcController(IProcessorFactory processorFactory)
{
_processorFactory = processorFactory;
}
public void Method()
{
var processor = _processorFactory.Create();
}
The best solution to your problem is to hide the knowledge of the existence of multiple implementations and the selection between them from the consumer by implementing a proxy implementation for IProcessor:
public sealed ProxyProcessor : IProcessor
{
private readonly ABCProcessor abc;
private readonly PQRProcessor pqr;
private readonly IProcessorConfig config;
public ProxyProcessor(ABCProcessor abc, PQRProcessor pqr, IProcessorConfig config) {
this.abc = abc;
this.pqr = pqr;
this.config = config;
}
// Implement IProcessor methods to forward to the CurrentProcessor.
public void Process() => CurrentProcessor.Process();
private IProcessor CurrentProcessor => config.ProcessorType == "ABC" ? abc : pqr;
}
By doing this you can delegate to the correct implementation at runtime while the consumer stays oblivious to the fact that you make a decision at runtime about this. Now instead of injecting either an ABCProcessor or PQRProcessor into the consumers, you now inject a ProxyProcessor into the consumers. For instance, this is how the object graph for the ProxyProcessor could look like:
IProcessor processor =
new ProxyProcessor(
abc: new ABCProcessor(),
pqr: new PQRProcessor(),
config: new SqlProcessorConfig("constr"));
Note that this solution has several benefits over the use of a factory, such as:
It prevents having to make any changes to the consumers; the consumers stay oblivious.
It prevents introducing unneeded complexity into the consumers; with the factory approach, consumers have to deal with with an extra dependency. This complicates code and tests.
It causes object graphs to be constructed in a delayed fashion, which complicates verification of object graphs.
Please read this article if you want to know more about why factories hardly ever are the right abstraction.

How to do logic based on object ID

Suppose I have a game, where there are buildings sorted by type. Each type is represented as a separate class, but sometimes I have to do some uncommon logic for the buildings of the same type. How could one implement this kind of behaviour?
For example, I can identify buildings by ID, so I can have a giant switch or command pattern inside the building type class. But I think that something is not right with this approach.
Another approach is to have different class for any divergent logic. But this proposes a lot of small classes.
This is what polymorphism aims to solve, and one of the big differences between procedural and oop programming. You can achieve it through extending a base class, or by implementing an interface. Here is extending a base class:
public abstract class Building {
abstract void destroy();
}
public BrickBuilding extends Building {
#Override
public void destroy() {
bricks.fallToGround();
}
}
public HayBuilding extends Building {
#Override
public void destroy() {
straw.blowInWind();
}
}
In places in your code where you would have used a switch statement to switch on building type, just hold a reference to the abstract Building type, and call method destroy() on it:
public class BuildingDestroyer {
public void rampage() {
for(Building building : allTheBuildings) {
// Could be a BrickBuilding, or a HayBuilding
building.destroy();
}
}
}
Or, to address your concern about having a lot of small types, you can 'inject' a destroy behaviour you want into a common building type, like so...albeing, you will end up with a lot of different destroy behaviour classes too...so, this might not be a solution.
public interface DestroyBehaviour {
void destroy(Building building);
}
public class Building {
private int id;
public DestroyBehaviour destroyBehaviour;
public Building(int id, DestroyBehaviour destroyBehaviour) {
this.id = id;
this.destroyBehaviour = destroyBehaviour;
}
public void destroy() {
destroyBehaviour.destroy(this); // or something along those lines;
}
}
You can get rid of the giant switch by having a BuildingFactory class which exposes a registerBuildingType(typeName, instanceCreatorFunc) method, that each building class calls (from a static initialize method for example) and that gets called with a unique string for that class (class name would suffice) and a static "create" method that returns a new instance.
This approach also has the advantage of being able to load new buildings from dynamically linked libraries.

Circular dependency when mapping parent and child entities to DTOs

I just implemented explicitly loading child entities along with their parents using in a generic repository using jevelez's method shown in this question.
However now i'm trying to map the child entities along with their parent entities to DTO's so i can send them to my UI layer.
Here's how my mappers currently look like:
The mapping interface:
public interface IMappingService<TEntity, TDto>
where TEntity : class
where TDto : class
{
TDto EntityToDto(TEntity entity);
TEntity DtoToEntity(TDto dto);
IEnumerable<TDto> EntitiesToDtos(IList<TEntity> entities);
IEnumerable<TEntity> DtosToEntities(IList<TDto> dtos);
}
The abstract base method that implements the interface:
public abstract class MapperBase<TEntity, TDto> : IMappingService<TEntity, TDto>
where TEntity : class
where TDto : class
{
public abstract TDto EntityToDto(TEntity entity);
public abstract TEntity DtoToEntity(TDto dto);
public virtual IEnumerable<TDto> EntitiesToDtos(IList<TEntity> entities)
{
return entities.Select(EntityToDto);
}
public virtual IEnumerable<TEntity> DtosToEntities(IList<TDto> dtos)
{
return dtos.Select(DtoToEntity);
}
}
Here's are two mappers that implement these for two entities as an example:
public class ParentEntityMapper : MapperBase<ParentEntity, ParentEntityDto> , IParentEntityMapper
{
private readonly IChildEntityMapper _childEntityMapper;
public ParentEntityMapper(IChildEntityMapper childEntityMapper)
{
_childEntityMapper = childEntityMapper;
}
public override ParentEntityDto EntityToDto(ParentEntity entity)
{
var dto = new ParentEntityDto();
dto.Id = entity.Id;
dto.Title = entity.Title;
dto.Description = entity.Description;
if (entity.ChildEntities != null)
{
dto.ChildEntities= _childEntityMapper.EntitiesToDtos(entity.ChildEntities .ToList()).ToList();
}
return dto;
}
public override ParentEntity DtoToEntity(ParentEntityDto dto)
{
// This is just a reverse of the above function
}
}
And the child entity mapper:
public class ChildEntityMapper : MapperBase<ChildEntity, ChildEntityDto>, IChildEntityMapper
{
private readonly ParentEntityMapper _parentEntityMapper;
public ChildEntityMapper(IParentEntityMapper parentEntityMapper)
{
_parentEntityMapper = parentEntityMapper;
}
public override ChildEntityDto EntityToDto(ChildEntity entity)
{
var dto = new ChildEntityDto();
dto.Id = entity.Id;
dto.Description = entity.Description;
if (entity.ParentEntity != null)
{
dto.ParentEntity = _parentEntityMapper.EntityToDto(entity.Image);
}
return dto;
}
public override Anchor DtoToEntity(AnchorDto dto)
{
// Just a reverse of the above function
}
}
So i sure you all can see where the circular dependency occurs. I've been agonizing over this for the past 2 days but I'm still pretty amateur at this and haven't been able to figure this out using Google thus far.
I prefer not to use tools like AutoMapper and ValueInjector for this part since i'm mapping between the database and DTO's and I'm already using it to map between the DTO's and the ViewModels in the UI layer.
If possible I'd like to be able to keep the mapping between the two this way since sometimes I'll be requesting just the child entities and in those cases I might want to get the parent entity along with it.
Does anyone know how this can be done properly?
I think I see where your "circular dependency" is coming in to play here, but just to be explicit, here's what I think would happen. You call EntityToDto on the ParentEntity, which in turn calls EntityToDto on all of the ChildEntity elements. Each of these ChildEntity elements in turn call EntityToDto on the ParentEntity and we are back to where we started from.
If that's the case my recommendation would be simple: don't have the child entity care EntityToDto on the parent. I would resolve at the root of the tree and then let everything below continue to resolve downward until the tree is complete.
If you did it this way, it would prevent the child entity from assigning the parent to itself. If you need to be able to traverse from the child to the parent, I'd have the parent assign itself to the child as the parent after the EntityToDto call was complete.
After thinking about it further i decided that instead of over complicating it that i would'nt allow getting a child entity with it's parent through the mapper but instead handle it for those few but specific scenarios in my service layer.
Anyone having the same problem can also check this thread i created on reddit for more information.