I am injecting in my services a global Settings interface, as Singleton, using StructureMap:
public interface ISettings {
LoggerSettings Logger { get; }
} // ISettings
public class LoggerSettings {
public String Levels { get { return ConfigurationManager.AppSettings["Logger.Levels"]; } }
public const String Report = "team#xyz.com";
} // LoggerSettings
public class Settings : ISettings {
public LoggerSettings Logger { get; private set; }
} // Settings
And as SM configuration I have:
For<ISettings>().Singleton().Use<Settings>();
I am able to inject this object but when I check the injected object its property Logger is null ... How can I have SM to initialize the object properties?
Am I missing something?
You need a constructor on the Settings class that has a LoggerSettings parameter so that StructureMap can set the Logger property on creation.
If you for some reason can't/don't want to use Constructor injection you need to make the setter on the Logger property on the Settings class public and configure property injection in StructureMap.
TL;DR: make Settings look like this:
public class Settings : ISettings {
public Settings(LoggerSettings logger)
{
Logger = logger;
}
public LoggerSettings Logger { get; private set; }
}
Related
I am trying to write some unit tests for an old system.
consider that I have a base class and a service like this :
public class BaseService
{
[Dependency]
public IBaseInterface _mybaseInterface { get; set; }
}
public class MyService : BaseService, IMyService
{
private readonly ISomeOtherInterface _myOtherInterface;
public MyService(ISomeOtherInterface myOtherInterface)
{
_myOtherInterface = myOtherInterface;
}
}
public class MyOtherService
{
private readonly IMyService _myservice;
public MyService(IMyService myservice)
{
_myservice = myservice
}
}
Question 1:
I am writing test for the MyOtherService class and I have to mock the IMyservice but I dont know how can I mock the interfaces in the base clas.
Question 2:
does converting the injection of the BaseService to constructor injection help me to mock the Myservice class dependencies ?
How do I map this:
public class Domain_1
{
public DomainType DomainType { get; set; }
public Domain_2 Domain2 { get; set; }
public Domain_3 Domain3 { get; set; }
}
to:
public abstract class DTOBase
{
// properties from Domain_1
}
public class DTO_1 : DTOBase
{
// properties from Domain_2
}
public class DTO_2 : DTOBase
{
// properties from Domain_3
}
Ideally,the Domain design should be same as the DTO but I can't due to EF6 and existing database restrictions.
Currently what I have right now is:
this.CreateMap<Domain_1, DTOBase>()
.ConstructUsing(SomeDTOCreatorFactoryMethod);
this.CreateMap<Domain_2, DTO_1>();
What SomeDTOCreatorFactoryMethod does is it creates the DTO based on the DomainType.
This works fine but I wanted to do some projection something like:
var domain_Db = dbContext.Domain1.Where(d => d.Id == 1).ProjectTo<DTOBase>.SingleOrDefault();
// var result = _mapper.Map<Domain1, DTOBase>(domain_Db);
Its throwing an error that cannot instantiate an abstract class. I understand the error but how I can use the factory method in order to create the DTO?
And what if I have to use a custom resolver on certain properties? I know this is not supported but is there a workaround?
I'm using MVC pattern in my application. For each model class I have a controller one. All controller classes have a saveOrUpdate() method. I am wondering if this is enough to create an Interface which defines said method, and then all controller implements it.
Please note that saveOrUpdate() receive a model class as a parameter. So it would be something like UserController#saveOrUpdate(User user), CourseController#saveOrUpdate(Course course), AppleManager#saveOrUpdate(Apple apple).
I think what you need is generic repository which implements generic functionality for a given entity. I've recently started implementing Repository Pattern along with Unit of Work in my MVC projects. Here is how I do that.
MyDbContext.cs:
public class MyDbContext : DbContext
{
public MyDbContext() : base("name=DefaultConnection”)
{
}
public System.Data.Entity.DbSet<User> Users { get; set; }
public System.Data.Entity.DbSet<Course> Courses { get; set; }
}
Unit of Work:
public class UnitOfWork : IUnitOfWork
{
//private variable for db context
private MyDbContext _context;
//initial db context variable when Unit of Work is constructed
public UnitOfWork()
{
_context = new MyDbContext();
}
//property to get db context
public MyDbContext Context
{
//if not null return current instance of db context else return new
get { return _context ?? (_context = new MyDbContext()); }
}
//save function to save changes using UnitOfWork
public void Save()
{
_context.SaveChanges();
}
}
Generic Repository:
public class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected readonly IUnitOfWork _unitOfWork;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_dbSet = _unitOfWork.Context.Set<T>();
}
public virtual void Save()
{
_unitOfWork.Save();
}
public virtual void Add(T entity)
{
_dbSet.Add(entity);
_unitOfWork.Save();
}
//Similarly you can have Update(), Delete(), GetAll() implementation here
}
Entity Repository inheriting from generic repo:
public class UserRepository:RepositoryBase<User>,IUserRepository
{
public UserRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
//Here you can also define functions specific to User
}
Controller:
public class UserController : Controller
{
private readonly IUserRepository _dbUserRepository;
public UserController(IUserRepository dbUserRepository)
{
_dbUserRepository = dbUserRepository;
}
// GET: /User/
public ActionResult Index()
{
var users = _dbUserRepository.GetAll();
return View(users.ToList());
}
}
create an interface
interface ISave
{
void Save(object obj);
}
now in your controller implement it.
public class AppleControler : Controller , ISave
{
public void Save(Object obj)
{
//you can cast your object here.
}
}
Option two
interface ISave<T>
{
void Save(T obj);
}
public class AppleControler : Controller , ISave<Apple>
{
public void Save(Apple obj)
{
}
}
I have a problem with Automapper when I try use custom resolver which uses dependency injection.
I have the following model:
public class User : Entity
{
public virtual string Name { get; set; }
public virtual Country Country { get; set; }
}
public class Country : Entity
{
public virtual string Name { get; set; }
}
and the following view model:
public class RegistrationViewModel
{
[Required]
public string Name { get; set; }
public int CountryId { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
in order to map I use the following code:
Mapper.Map(registrationViewModel, user);
earlier I register the following:
Mapper.Reset();
container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<ISession>().
UsingFactoryMethod(() => NHibernateSessionFactory.RetrieveSession()).
LifeStyle.Is(LifestyleType.Transient));
container.Register(Component.For(typeof(LoadingEntityResolver<>)).ImplementedBy(typeof(LoadingEntityResolver<>)).LifeStyle.Transient);
Mapper.Initialize(x =>
{
x.AddProfile<BasicProfile>();
x.ConstructServicesUsing(container.Resolve);
});
My BasicProfile is the following:
public class BasicProfile : Profile
{
public const string VIEW_MODEL = "MyBasicProfile";
public override string ProfileName
{
get { return VIEW_MODEL; }
}
protected override void Configure()
{
CreateMaps();
}
private void CreateMaps()
{
CreateMap<RegistrationViewModel, User>()
.ForMember(dest => dest.Country, _ => _.ResolveUsing<LoadingEntityResolver<Country>>().FromMember(src => src.CountryId))
);
}
}
The custom resolver is done in the following way:
public class LoadingEntityResolver<TEntity> : ValueResolver<int, TEntity>
where TEntity: Entity
{
private readonly ISession _session;
public LoadingEntityResolver(ISession session)
{
_session = session;
}
protected override TEntity ResolveCore(int source)
{
return _session.Load<TEntity>(source);
}
}
When the mapping code is being run I get the following exception:
AutoMapper.AutoMapperMappingException : Trying to map ViewModels.RegistrationViewModel to Models.User.
Using mapping configuration for ViewModels.RegistrationViewModel to Models.User
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
----> AutoMapper.AutoMapperMappingException : Trying to map ViewModels.RegistrationViewModel to LModels.Country.
Using mapping configuration for ViewModels.RegistrationViewModel to Models.User
Destination property: Country
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
----> System.ArgumentException : Type 'Mapping.LoadingEntityResolver`1[Models.Country]' does not have a default constructor
I have no idea what may be wrong. It is probably something with constructing the resolver. When I try the following there is no problem:
var resolver = container.Resolve<LoadingEntityResolver<Country>>();
Assert.IsInstanceOf<LoadingEntityResolver<Country>>(resolver);
I would be greatfull for any help.
Best regards
Lukasz
You have some pretty hefty DI stuff going on here :-) I would avoid having AutoMapper resolve entities from a database or whatever. Makes the code difficult to understand and following objects lifetime could become a nightmare.
Anyway, to fix your problem simply swap the order from (wrong):
Mapper.Initialize(x =>
{
x.AddProfile<BasicProfile>();
x.ConstructServicesUsing(container.Resolve);
});
to (correct):
Mapper.Initialize(x =>
{
x.ConstructServicesUsing(container.Resolve);
x.AddProfile<BasicProfile>();
});
public interface IMyInterface
{
int A { get; set; }
string S { get; set; }
}
public abstract class MyAbs : IMyInterface
{ }
public class ConcreteClass : MyAbs
{
/* Implementation of IMyInterface*/
}
Is it possible to omit the empty implementation in an abstract class as above?
If so, how? why?
you can define the methods/properties as abstract in the abstract class so it won't have empty implementation
The code you provided will not compile
what you need is
public interface IMyInterface
{
int A
{ get; set; }
string S
{ get; set; }
}
public abstract class MyAbs : IMyInterface
{
public abstract int A { get; set; }
public abstract string S { get; set; }
}
public class ConcreteClass : MyAbs
{
/* Implementation of IMyInterface*/
}
The purpose of an abstract class is to encapsulate some common behaviour that applies to all the deriving classes. If you haven't got anything at all in your abstract class then it there is no purpose to having it, ConcreteClass should implement the interface directly.
If you subsequently add another class that also implements this behaviour, then that is the time to refactor and create an abstract base class if it makes sense.