nonComVisibleBaseClass Error when moq a Com interface - moq

I used moq version 4.0.10827 to mock an Com object and when i upgrade to 4.2.1510.2205 i get an nonComVisibleBaseClass error when the test execute:
[Guid("0339CD56-9BA3-477D-801B-E5F73D37EABE")]
[TypeLibType(4160)]
public interface IDaemonCli
{
// methods & propperties ...
[DispId(1)]
void CloseLog();
....
}
[CoClass(typeof(DaemonCliClass))]
[Guid("0339CD56-9BA3-477D-801B-E5F73D37EABE")]
public interface DaemonCli : IDaemonCli
{
}
[ClassInterface(0)]
[Guid("D94FBC81-06EC-4EAA-B73F-794051487691")]
[TypeLibType(2)]
public class DaemonCliClass : IDaemonCli, DaemonCli
{
// ... definitions of all methods of the com obj
[DispId(1)]
public virtual void CloseLog();
....
}
The mock is created as this :
[TestClass]
[Serializable]
public abstract class Test : IDisposable
{
protected static Mock<DaemonCli> DaemonClientMock { get; private set; }
static Test()
{
Test.DaemonClientMock = new Mock<DaemonCli>();
// here are all the setup on the DaemonClientMock
}
}
The mock is injected in the tested code as this :
typeof(LoggedServiceBase).GetProperty(
PropertySupport.ExtractPropertyName(() => this.batchClassService.Logger),
BindingFlags.Public | BindingFlags.Instance)
.SetValue(this.batchClassService, Test.DaemonClientMock.Object, null);
The Exception is raised when the mock is used by the tested class:
freeMindCom.SetLog(this.Logger);
All was fine with the version of Castle used by the previous version of Moq (4.0.10.827), i don't know precisely which one it was.
Any help would be appreciated.
Thanks

Related

Unity and Repository pattern

Hi I am using a UOW and Repository pattern in my project and I have created the following code:
// Interfaces
public interface IUnitOfWork : IDisposable
{
IGenericRepository<Company> CompanyRepository { get; }
void Commit();
}
public interface IEFUOW_Company : IUnitOfWork
{
bool CreateCompanyForUser(RegisterModel model, string userName);
}
// Implementation
public class EFUOW_Company : EfUnitOfWork
{
public EFUOW_Company()
{
}
}
public class EfUnitOfWork : Disposable, IUnitOfWork
{
private DALDbContext _dataContext;
private EfGenericRepository<Company> _companyRepo;
public DbSet<Company> Companies { get; set; }
public EfUnitOfWork()
{
_companyRepo = null;
}
}
// Unity Registration
container.RegisterType<IUnitOfWork, EfUnitOfWork>(new HttpContextLifetimeManager<IUnitOfWork>());
.RegisterType<IEFUOW_Company, EFUOW_Company>(new HttpContextLifetimeManager<IEFUOW_Company>());
// Error Message # Compile
Error 105 The type 'DataAccessLayer.UnitOfWork.EFUOW_Company' cannot be used as type parameter 'TTo' in the generic type or method
'Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<TFrom,TTo>(Microsoft.Practices.Unity.IUnityContainer, Microsoft.Practices.Unity.L
ifetimeManager, params Microsoft.Practices.Unity.InjectionMember[])'. There is no implicit reference conversion from '
DataAccessLayer.UnitOfWork.EFUOW_Company' to 'DataAccessLayer.UnitOfWork.IEFUOW_Company'.
I cannot work out why it's complaining about the conversion as I am new to Unity and this is my first attempt at building this type of logic.
I want to be able to create different IUnitOfWork based interfaces/implementations so I can reuse code in the IUnitOfwork and it's Implementation EfUnitOfWork.
Thanks in advance
The class efuow_company does not implement iefuow_company interface.

Proper way of using Unit of Work with unity injection

I am using unity, entity framework 4 with POCO classes, repository pattern for DAL and services for Business Logic control.
I also want to use Unit of Work so I can package together CRUD operations which I perform on different services and then commit them all together.
My question is what would be the proper way to inject the Unit Of Work mechanism into my application using Microsoft Unity?
I understand that I can put the IUnitOfWork together with the repository on the constructor of the proper service and then if Unity mapping is specified it would auto initiate the proper instances, but this way I do not pass the global unit of work but rather create a new instance on each level, which can't be a smart way to do it (actually the repository is initiated even before the service).
What am I missing? (Attached is constructor code as I wrote it now of service and its repository).
U also understand that I can use Unity's ParameterOverrides method to take some global instance of Unit of Work (lets say from my aspx.cs file) and pass it into the service and then into the repository. But it seems a bit lame. Is this my only option?
Thanks
public class GenericRepository<T> : IUnitOfWorkRepository, IGenericRepository<T> where T : BaseEntity, IAggregateRoot
{
private IUnitOfWork _uow;
/// <summary>
/// Returns the active object context
/// </summary>
private ObjectContext ObjectContext
{
get
{
return ObjectContextManager.GetObjectContext();
}
}
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
//blahhhh...
public void Add(T entity)
{
_uow.RegisterNew(entity, this);
}
public void Delete(T entity)
{
_uow.RegisterRemoved(entity, this);
}
//.....blah blah....
public void PersistCreationOf(IAggregateRoot entity)
{
this.ObjectContext.AddObject(GetEntitySetName(), entity);
}
public void PersistUpdateOf(IAggregateRoot entity)
{
// Do nothing as EF tracks changes
}
public void PersistDeletionOf(IAggregateRoot entity)
{
this.ObjectContext.DeleteObject(entity);
}
}
public class CategoryRepository : GenericRepository<XComSolutions.FB.Domain.Model.Entities.Category>, ICategoryRepository
{
public CategoryRepository(IUnitOfWork uow)
: base(uow)
{ }
}
public class CategoryService : ICategoryService
{
public int myID {get; set;}
private ICategoryRepository _categoryRepository;
private IUnitOfWork _uow;
public CategoryService(ICategoryRepository categoryRepository,
IUnitOfWork uow)
{
_categoryRepository = categoryRepository;
_uow = uow;
}
public List<Category> GetAll()
{
return _categoryRepository.GetAll();
}
}
Define an IUnitOfWorkFactory and inject that in your services:
public class Service
{
private readonly IUnitOfWorkFactory factory;
public Service(IUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void DoOperation()
{
using (UnitOfWork context = this.factory.CreateNew())
{
this.DoSomeStuff(context);
this.DoMoreStuff(context);
context.SubmitChanges();
}
}
}
What I think you need to do is to define unit of work factory. You register this factory with your DI container and you resolve for this factory every time you need your unit of work. Then you get unit of work from the factory, work with it and let it go. You often will see that you need your unit of work within a scope of single method or single class. This article discuss Unit of Work pattern in connection with Entity Framework: http://msdn.microsoft.com/en-us/magazine/dd882510.aspx

WCF Runtime Error while using Constructor

I am new to WCF i am using constructor in my WCF service.svc.cs file....It throws this error when i use the constructor
The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor.
To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.
When i remove the constructor its working fine....But its compulsory that i have to use constructor...
This is my code
namespace UserAuthentication
{
[ServiceBehavior(InstanceContextMode=System.ServiceModel.InstanceContextMode.Single)]
public class UserAuthentication : UserRepository,IUserAuthentication
{
private ISqlMapper _mapper;
private IRoleRepository _roleRepository;
public UserAuthentication(ISqlMapper mapper): base(mapper)
{
_mapper = mapper;
_roleRepository = new RoleRepository(_mapper);
}
public string EduvisionLogin(EduvisionUser aUser, int SchoolID)
{
UserRepository sampleCode= new UserRepository(_mapper);
sampleCode.Login(aUser);
return "Login Success";
}
}
}
can anyone provide ideas or suggestions or sample code hw to resolve this issue...
You could add something like (if possible):
public UserAuth() : this(SqlMapperFactory.Create())
{
}

ASP.Net MVC TDD using Moq

I am trying to learn TDD/BDD using NUnit and Moq.
The design that I have been following passes a DataService class to my controller to provide access to repositories.
I would like to Mock the DataService class to allow testing of the controllers.
There are lots of examples of mocking a repository passed to the controller but I can't work out how to mock a DataService class in this
scenerio.
Could someone please explain how to implement this?
Here's a sample of the relevant code:
[Test]
public void Can_View_A_Single_Page_Of_Lists()
{
var dataService = new Mock<DataService>();
var controller = new ListsController(dataService);
...
}
namespace Services
{
public class DataService
{
private readonly IKeyedRepository<int, FavList> FavListRepository;
private readonly IUnitOfWork unitOfWork;
public FavListService FavLists { get; private set; }
public DataService(IKeyedRepository<int, FavList> FavListRepository,
IUnitOfWork unitOfWork)
{
this.FavListRepository = FavListRepository;
this.unitOfWork = unitOfWork;
FavLists = new FavListService(FavListRepository);
}
public void Commit()
{
unitOfWork.Commit();
}
}
}
namespace MyListsWebsite.Controllers
{
public class ListsController : Controller
{
private readonly DataService dataService;
public ListsController(DataService dataService)
{
this.dataService = dataService;
}
public ActionResult Index()
{
var myLists = dataService.FavLists.All().ToList();
return View(myLists);
}
}
}
Create an interface like this:
public interface DataService
{
FavListService FavLists { get; }
void Commit();
}
Make your DataService implement this interface and your controller should depend on this interface. Problem solved :)
EDIT: This line of code:
dataService.FavLists.All().ToList();
is breaking the law of demeter and will be a pain to unit test your service. Create a method like AllFavList() on your service instead of all these chain of calls, it will be easier to mock.
EDIT2: How to mock you get property
dataService.SetupGet(d => d.FavLists).Returns(your_variable);

Ninject giving NullReferenceException

I'm using asp.net MVC 2 and Ninject 2.
The setup is very simple.
Controller calls service that calls repository.
In my controller I use inject to instantiate the service classes with no problem. But the service classes don't instantiate the repositories, giving me NullReferenceException.
public class BaseController : Controller
{
[Inject]
public IRoundService roundService { get; set; }
}
This works. But then this does not...
public class BaseService
{
[Inject]
public IRoundRepository roundRepository { get; set; }
}
Giving a NullReferenceException, when I try to use the roundRepository in my RoundService class.
IList<Round> rounds = roundRepository.GetRounds( );
Module classes -
public class ServiceModule : NinjectModule
{
public override void Load( )
{
Bind<IRoundService>( ).To<RoundService>( ).InRequestScope( );
}
}
public class RepositoryModule : NinjectModule
{
public override void Load( )
{
Bind<IRoundRepository>( ).To<RoundRepository>( ).InRequestScope( );
}
}
In global.axax.cs
protected override IKernel CreateKernel( )
{
return new StandardKernel( new ServiceModule( ),
new RepositoryModule( ) );
}
Have you thought about using constructor injection?
That's how I do my dependency injection with Ninject 2 & ASP.NET MVC 2 and it works all the way down the chain from controller -> service -> repository & beyond.
It also makes sense to me to have the dependencies in the constructor for your object. It makes these dependencies highly visible and obvious to any other object that has to instantiate it. Otherwise you may end up with null reference exceptions... kinda like you have here.
HTHs,
Charles
EDIT: Showing base class injection through constructors in response to the comments.
public class BaseService
{
public IRoundRepository RoundRepo { get; private set; }
public BaseService(IRoundRepository roundRepo)
{
RoundRepo = roundRepo;
}
}
public class SquareService : BaseService
{
public ISquareRepository SquareRepo { get; private set; }
public SquareService(ISquareRepository squareRepo, IRoundRepository roundRepo)
: base(roundRepo)
{
SquareRepo = squareRepo;
}
}
This is just my way of doing things... someone else may have a different idea / opinion.

Resources