Autofac, multiple interfaces to same implementation per HTTP request in ASP.NET MVC - asp.net-mvc

My DbContext implementation implements two interfaces.
I'm trying to follow best practices and instantiate one DbContext instance per HTTP request.
However, I have a controller action where I need to instantiate two classes, each of which takes different interface in constructor.
I am worried if in that scenario, for that specific action, two DbContext instances would be raised.
I've setup my ContainerBuilder like this:
builder.RegisterType<MyDbContext>()
.As<IWorkflowPersistenceStore>()
.As<IDocumentPersistenceStore>()
.InstancePerHttpRequest();
builder.RegisterType<WorkflowManager>().As<IWorkflowManager>().InstancePerHttpRequest();
builder.RegisterType<DocumentManager>().As<IDocumentManager>().InstancePerHttpRequest();
public class OperationController : Controller
{
private IWorkflowManager _workflowManager;
private IDocumentManager _documentManager;
public OperationController(IWorkflowManager workflowManager, IDocumentManager documentManager)
{
_workflowManager = workflowManager;
_documentManager = documentManager;
}
public ActionResult SaveWorkflowDocument(...)
{
// will my managers point to same DbContext?
_workflowManager.DoSomething(...);
_documentManager.DoSomethingElse(...);
return View();
}
}
public class WorkflowManager : IWorkflowManager
{
private IWorkflowPersistenceStore _store;
public WorkflowManager(IWorkflowPersistenceStore store)
{
_store = store;
}
}
public class DocumentManager : IDocumentManager
{
private IDocumentPersistenceStore _store;
public DocumentManager (IDocumentPersistenceStore store)
{
_store = store;
}
}
Is this good enough?
Do I have to add .SingleInstance()? I'm worried that it might create singleton for whole application.

I think you're ok with what you have. Test passes:
using Autofac;
using NUnit.Framework;
namespace AutofacTest
{
[TestFixture]
public class ScopeTest
{
[Test]
public void Test()
{
var builder = new ContainerBuilder();
builder.RegisterType<Component>()
.As<IServiceA>()
.As<IServiceB>()
.InstancePerLifetimeScope();
using (var container = builder.Build())
using (var scope = container.BeginLifetimeScope())
{
var a = scope.Resolve<IServiceA>();
var b = scope.Resolve<IServiceB>();
Assert.AreEqual(a, b);
}
}
}
public interface IServiceA { }
public interface IServiceB { }
public class Component : IServiceA, IServiceB { }
}

Related

Unit Testing a mock WCF client

I'm having serious issues in how to deploy a WCF client in a MVC site which is easily testable. I'm struggling to set up a mock of the service without actually accessing a endpoint.
Example Controller of site under test
public class ProfileController : ControllerExtended
{
public ProfileController(IUserService membershipService, IDropDownService dropdownService, ISiteService siteService)
{
WCFService.Instance.Client = siteService; //Should maybe be a serpate service.
_membershipService = membershipService;
_dropDownService = dropdownService;
_siteService = siteService;
}
public ActionResult Index()
{
UserComp profile = _siteService.ProfileGet(_sharedContext.CurrentUser.id);
return View(new ProfileViewModel { Profile = profile });
}
}
WCF Singleton (I think my implementation of WCF is my issue, should it be in a interface?)
public sealed class WCFService
{
public SiteServiceI Client { get; set; }
#region Singleton
static readonly WCFService query = new WCFService();
static WCFService()
{
}
WCFService()
{
}
public static WCFService Instance
{
get { return query; }
}
#endregion
}
UnitTest
[TestFixture]
public class UnitTest1
{
private Mock<SiteService> mockSiteService;
private Mock<IUserService> mockMembershipService;
private Mock<IDropDownService> mockDropDown;
private Mock<SiteServiceIClient> mockServiceClient; //new Mock<SiteServiceIClient>();
//private Mock<WebService> mockWebService;
[SetUp]
public void SetUp()
{
mockSiteService = new Mock<ISiteService>();
mockMembershipService = new Mock<IUserService>();
mockDropDown = new Mock<IDropDownService>();
mockServiceClient = new Mock<SiteServiceIClient>();
mockWebService = new Mock<WebService>(mockServiceClient);
}
[Test]
public void CheckHomeIndex_Controller()
{
var controller = new HomeController(mockMembershipService.Object, mockDropDown.Object, mockPTSearch.Object, mockServiceClient.Object); // mockServiceClient times out.
Assert.AreEqual("this", "this");
}
}
I assume the errors are occurring because the singleton sets the service up as soon as it is initialised. I've tried to implement a separate service purely for called to WCF but not had success in implementing it in a testable manner. Not too sure if this is to vague but I've read a lot on it and not an closer.
The singleton is definitely your problem - testing with singletons is entering a world of pain. You should implement a facade pattern to make this testing friendly. Something like this:
public interface IServiceFacade
{
Profile ProfileGet(int id);
}
public class ServiceFacade : IServiceFacade
{
private WCFService _theRealService = new WCFService();
public Profile ProfileGet(int id)
{
return _theRealService.ProfileGet(id);
}
}
public class Some_Tests()
{
public void Test_Stuff_Whatever()
{
Mock<IServiceFacade> _facade = new Mock<IServiceFacade>();
_facade.SetUp(Whatever.....);
}
}
Your problem is that your service is singleton. The problem of singleton pattern is that it is not testable. You should use Dependency injection to get service.

How to use Ninject to create instances in child classes?

I am learning how to use nInject for a new application I am developing, and I have created the following sample code that can be copied/pasted into a simple console app. It successfully returns an instance of IFoo, but I have a question about it.
How would I modify the code to have the FooManager class create an instance of the Foo object without doing a 'new'. Does the kernal have to be injected as well? But if the kernal is injected and I change the line to read var foo = _kernel.Get<IFoo>(), isn't that introducing a service locator anti-pattern?
namespace IOCTest
{
class Program
{
static void Main(string[] args)
{
using (IKernel kernel = new StandardKernel(new StandardModule()))
{
// do something with the kernal
var mgr = kernel.Get<IFooManager>();
var foo = mgr.GetById(1);
}
}
}
public class StandardModule : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IDatabase>()
.To<Database>()
.InTransientScope();
Bind<IFooManager>()
.To<FooManager>()
.InTransientScope();
}
}
//******************************************************
public interface IDatabase
{
object[] GetScalar(int id);
}
public class Database : IDatabase
{
public object[] GetScalar(int id)
{
return new object[] { "RowName" };
}
}
//******************************************************
public interface IFooManager
{
IFoo GetById(int id);
}
public class FooManager : IFooManager
{
private IDatabase _db;
public FooManager(IDatabase db) { _db = db; }
public IFoo GetById(int id)
{
var results = _db.GetScalar(id);
var foo = new Foo(); // <-- HOW DO I ELIMINATE THIS DEPENDENCY?
foo.Name = results[0].ToString();
return foo;
}
}
//******************************************************
public interface IFoo
{
string Name { get; set; }
}
public class Foo : IFoo
{
public string Name { get; set; }
}
//******************************************************
}
First you have to think about the purpose of Foo. Is this some kind of a datacontainer or some service?
In the first case your code is perfect like it is. Datacontainers have no dependencies and shouldn't be created by the IoC container.
In the second case read about Ninject.Extensions.Factory.
http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
https://github.com/ninject/ninject.extensions.factory/wiki
There are a couple ways to eliminate that dependency. You could do the same thing you did with the Database dependency and use constructor injection. You could do property injection (https://github.com/ninject/ninject/wiki/Injection-Patterns). Another way, and perhaps what you are looking for, would be service location. To do that you can update your FooManager ctor to require an IKernel. This will be resolved automatically and you can then use the kernel that is passed in to get Foo.
public class FooManager : IFooManager
{
private IDatabase _db;
private IKernel _kernel;
public FooManager(IDatabase db, IKernel kernel) { _db = db; _kernel = kernel;}
public IFoo GetById(int id)
{
var results = _db.GetScalar(id);
// var foo = new Foo(); // <-- HOW DO I ELIMINATE THIS DEPENDENCY?
var foo = kernel.Get<IFoo>(); // Like this perhaps
foo.Name = results[0].ToString();
return foo;
}
}

Implementation-less typed factory issues

Take this simple example:
class Program
{
static void Main(string[] args)
{
var windsorContainer = new WindsorContainer();
windsorContainer.Install(new WindsorInstaller());
var editor = windsorContainer.Resolve<IEditor>();
editor.DoSomething();
Console.ReadKey();
}
}
public class WindsorInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ISomeOtherDependency>().ImplementedBy<SomeOtherDependency>());
container.Register(Component.For<IReviewingService>().ImplementedBy<ReviewingService>());
container.Register(Component.For<IEditor>().ImplementedBy<Editor>());
container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
}
}
public interface IEditor
{
void DoSomething();
}
public class Editor : IEditor
{
private readonly Func<IReviewingServiceFactory> _reviewingService;
public Editor(Func<IReviewingServiceFactory> reviewingService)
{
_reviewingService = reviewingService;
}
public void DoSomething()
{
var rs = _reviewingService();
var reviews = new List<string> {"Review #1", "Review #2"};
var reviewingService = rs.Create(reviews);
reviewingService.Review();
}
}
public interface IReviewingServiceFactory
{
IReviewingService Create(IList<string> reviews);
}
public interface IReviewingService
{
void Review();
}
public class ReviewingService : IReviewingService
{
private readonly IList<string> _reviews;
private readonly ISomeOtherDependency _someOtherDependency;
public ReviewingService(IList<string> reviews, ISomeOtherDependency someOtherDependency)
{
_reviews = reviews;
_someOtherDependency = someOtherDependency;
}
public void Review()
{
Console.WriteLine("Reviewing...");
}
}
public interface ISomeOtherDependency
{
}
public class SomeOtherDependency : ISomeOtherDependency
{
}
With this example I would expect the console to output "Reviewing...". However, Windsor throws exceptions:
No component for supporting the service CastleWindsorTypedFactor.IReviewingServiceFactory was found
What is wrong with my Windsor installer?
You registered Func<IReviewingServiceFactory> instead of IReviewingServiceFactory... try replacing
container.Register(Component.For<Func<IReviewingServiceFactory>>().AsFactory());
with
container.Register(Component.For<IReviewingServiceFactory>().AsFactory());
and adapt the code accordingly - then it should work.
Oh, and another thing - you registered your IReviewingService without specifying a lifestyle, which will default to SINGLETON. That is most likely not what you want, because then your reviews argument will only be passed to the instance when is gets created, which only happens the first time the factory is called...! Additional calls to the factory will return the singleton instance.
Therefore: Change the lifestyle of IReviewingService to transient, AND create an appropriate release method signature on the factory interface (e.g. void Destroy(IReviewingService service)).

How to avoid repositories that duplicate code

I have successfully setup a simple mvc application that lists teams. I'm using Ninject to inject the appropriate repository depending on the controller (thanks to stack overflow ;). All looks good, except that the repository code looks exactly the same. And I know that's wrong. So my TeamRepository has two classes (for now).
public class SwimTeamRepository : ITeamRepository<SwimTeam>
{
private readonly Table<SwimTeam> _teamTable;
public SwimTeamRepository(string connectionString)
{
_teamTable = (new DataContext(connectionString).GetTable<SwimTeam>());
}
public IQueryable<SwimTeam> Team
{
get { return _teamTable; }
}
}
public class SoccerTeamRepository : ITeamRepository<SoccerTeam>
{
private readonly Table<SoccerTeam> _teamTable;
public SoccerTeamRepository(string connectionString)
{
_teamTable = (new DataContext(connectionString).GetTable<SoccerTeam>());
}
public IQueryable<SoccerTeam> Team
{
get { return _teamTable; }
}
}
They look exactly the same except for the Class and Table name, so clearly I need to re-factor this. What would be the best approach here? Singleton? Factory Method?
Thanks in advance!
You could use generics:
public interface ITeamRepository<T>
{
}
public class TeamRepository<TTeam> : ITeamRepository<TTeam>
where TTeam : Team
{
private readonly Table<TTeam> _teamTable;
public TeamRepository(string connectionString)
{
_teamTable = (new DataContext(connectionString).GetTable<TTeam>());
}
public IQueryable<TTeam> Team
{
get { return _teamTable; }
}
}
public class Team
{
}
public class SwimTeam : Team
{
}
Then use it like so...
public void MyMethod()
{
var repository = new TeamRepository<SwimTeam>();
}
...and set up your IoC container w/ Ninject like so...
public class MyModule : NinjectModule
{
public override void Load()
{
Bind<ITeamRepository<SwimTeam>>
.To<TeamRepository<SwimTeam>>();
}
}
public void MyMethod()
{
var repository = kernel.Get<ITeamRepository<SwimTeam>>();
}
If you want to get REAL generic and have a single repository for ALL of your mapped classes, you can do something like this:
public interface IRepository
{
IQueryable<T> Get<T>() where T : class, new();
}
public class Repository : IRepository, IDisposable
{
private DataContext _dataContext;
public Repository(string connectionString)
{
_dataContext = new DataContext(connectionString);
}
public IQueryable<T> Get<T>()
where T : class, new()
{
return _dataContext.GetTable<T>().AsQueryable();
}
public void Dispose()
{
if (_dataContext != null)
{
_dataContext.Dispose();
_dataContext = null;
}
}
}
...which you could call like so (after setting up your Ninject container)...
using (var repository = kernel.Get<IRepository>())
{
var swimTeam = repository.Get<SwimTeam>();
}
Since Ninject takes care of the life-cycle management of your objects, you don't HAVE to wrap the repository in a using statement. In fact, you don't want to use a using statement there at all if you plan to use the repository more than once within the scope of its lifetime. Ninject will automatically dispose of it when it's life-cycle ends.
Here's a good article by Rob Conery on using this kind of technique to reduce the friction of using different ORMs.
EDIT by keeg:
I Think
public class TeamRepository<TTeam> : ITeamRepository<TTeam> where TTeam : Team {}
Should be
public class TeamRepository<TTeam> : ITeamRepository<TTeam> where TTeam : class {}
Please correct if I'm wrong.
Is this what you want?
public class TeamRepository : ITeamRepository<T>
{
private readonly Table<T> _teamTable;
public TeamRepository(string connectionString)
{
_teamTable = (new DataContext(connectionString).GetTable<T>());
}
public IQueryable<T> Team
{
get { return _teamTable; }
}
}

MVC 3 + IoC + NInject + Repositories + LINQ

I'm trying to work with NInject in my MVC 3 application, and i have one question.
Interface
public interface ITalesRepository
{
IEnumerable<Tale> GetAllTales();
}
Repository
public class TalesRepository : ITalesRepository
{
private FairyTalesMVC3DataContext _dataContext;
public TalesRepository(FairyTalesMVC3DataContext dataContext)
{
_dataContext = dataContext;
}
public IEnumerable<Tale> GetAllTales()
{
return _dataContext.Tales.OrderBy(c => c.NameAn);
}
}
Home controller
public class HomeController : Controller
{
private readonly ITalesRepository _talesRepository;
public HomeController(ITalesRepository talesRepository)
{
_talesRepository = talesRepository;
}
public ActionResult Index()
{
ViewBag.Tales = _talesRepository.GetAllTales();
return View();
}
}
So, i need to initialize my TalesRepository with DataContext, and now it is so:
private void RegisterDependencyResolver()
{
var kernel = new StandardKernel();
kernel.Bind<ITalesRepository>().To<TalesRepository>().WithConstructorArgument("dataContext", new FairyTalesMVC3DataContext(ConfigurationManager.ConnectionStrings["dbFairyTalesConnectionString"].ConnectionString));
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
So, my question, is it ok or something wrong?
First of all:
public IEnumerable<Tale> GetAllTales()
{
return _dataContext.Tales.OrderBy(c => c.NameAn);
}
I would add .ToList() to the end. Else you'll get data layer exceptions in your presentation layer which is not fine.
Next, I would recommend that you switch to ViewModels instead of using ViewBag. It's a lot easier to prevent that logic leaks into the views if you are using ViewModels. Since you can add the logic to the ViewModel and thus get the same behaviour in all views using the model.
Your application should inherit from NinjectHttpApplication. It registers dependency resolver, so you don't have to do it.
You should also override CreateKernel in application class and register your own module with bindings:
public class MvcApplication : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
return new StandardKernel(new INinjectModule[] {new MvcModule()});
}
}
public class MvcModule : NinjectModule
{
public override void Load()
{
Bind<ITalesRepository>().To<TalesRepository>();
Bind<FairyTalesMVC3DataContext>().To<FairyTalesMVC3DataContext>().InRequestScope();
}
}

Resources