I have 3 service components, one low-level service responsible for some kind of data serialization, one in the middle responsible for coordinating saves/loads, and one MVC Controller responsible for API publication.
Each of the 3 components logically refers to the other "below" it. The middle service has another parameter, which is known at runtime, based on request data. From this 3 components the controller and the middle service are represented by classes (doesn't make sense to introduce interfaces because nothing to mock), and the lowest level is repesented by an interface, making it available to unit-test the middle service or the controller. I'd like to use DI (specifically Ninject) to build my controller class. My question is if any kind of best practice exists for handling this scenario. Currently I see two way of implementation. (The validations, proper implementations are ommitted for the clarity.)
First of all, here is a sample implementation of the middle service and the lower level interface.
public interface ISerializer {
void Serialize(object data);
}
public class MyService {
private string _dataId;
private ISerializer _serializer;
public MyService(string dataId, ISerializer serializer) {
_serializer = serializer;
_dataId = dataId;
}
public bool CanProcess(MyDTO data) {
...
}
public void DoSomeProcessing(MyDTO data) {
...
}
}
Version 1: inject the whole middle service to the controller as a factory
public class MyController : Controller {
private Func<string, MyService> _myServiceFactory;
public MyController(Func<string, MyService> myServiceFactory) {
_myServiceFactory = myServiceFactory;
}
...
[HttpPost]
public JsonResult Process(string dataId, MyDTO model) {
using (var myService = _myServiceFactory(dataId)) {
...
if (myService.CanProcess(model))
myService.DoSomeProcessing(model);
...
return Json("ok");
}
}
}
Version 2: Injecting directly the lower-level interface to the controller, and instantiate the middle service "manually".
public class MyController : Controller {
private ISerializer _serializer;
public MyController(ISerializer serializer) {
_serializer = serializer;
}
...
[HttpPost]
public JsonResult Process(string dataId, MyDTO model) {
using (var myService = new MyService(dataId, _serializer) {
...
if (myService.CanProcess(model))
myService.DoSomeProcessing(model);
...
return Json("ok");
}
}
}
Which one is more proper, or should I choose a completely different solution?
First of all, I like my services to be stateless, so I don't like the idea of passing dataId
to the service's constructor. When services are stateless they are safer. You can call their methods not worrying if they are currently in a valid state. It also makes it easier to test and mock them. You can also reduce the amount of used memory, as you only need one instance of a stateless service.
If you moved dataId to DoSomeProcessing as a parameter you would be able to easily instantiate MyService with Ninject and the proper implementation of ISerializer would be injected automatically.
However if you insist on passing it to the constructor "Version 1" is quite close to what I'd consider good. Factory is a nice trick to let DI inject dependencies, when there are also data parameters needed in the constructor. I would inject MyServiceFactory to the controller. I'd create another class for it:
public class MyServiceFactory : IMyServiceFactory // an interface to me able to mock it if needed
{
ISerializer _serializer;
MyServiceFactory(ISerializer serializer){ // here Ninject can inject the dependency
_serializer = serializer;
}
IMyService Create(int dataId){ // here you can pass additional parameter
return new MyService(dataId, _serializer);
}
}
This way you can easily avoid hard dependencies and make the code more maintainable and more testable.
"Version 2" is wrong. If you ever want to test your controller or replace MyService with another implementation - you are stuck. You'll have to do a lot of tedious refactoring (depending on the amount of usages). And finally you'll end up with something similar to what I suggested above. :)
Related
I generate a singleton at runtime
public void ConfigureServices(IServiceCollection services)
{
var applications = Utils.generateApplications()
services.AddSingleton<ApplicationModel[]>(applications);
services.AddMvc();
}
How can I later update this dependency injected ApplicationModel[] with a completely new ApplicationModel[]. I have a feature in my application that the user can use to trigger a data refresh on the applications, but how can I update the underlying injected Singleton so all future injections will use the updated applications? I have a function Utils.generateApplications() that gets an up to date list of applications and returns a ApplicationModel[]. How do I overwrite the old injected Singleton with a new object to be injected into future calls if that makes sense?
I have some code :
public void UpdateData()
{
var applications = Utils.generateApplications()
//How do I set applications to replace the injected singleton for all future injections?
}
You should use an additional layer of indirection. I think the simplest way is to use an abstract factory. Define an interface something like this:
interface IApplicationModelFactory
{
public ApplicationModel[] GetModel();
}
Define a second interface with the method (or methods) needed to update the model:
interface IApplicationModelUpdate
{
void UpdateModel();
}
You can then change your ApplicationModel[] registration from single instance to scoped and delegate to the factory:
var modelFactory = new ApplicationModelFactory();
services.AddSingleton<IApplicationModelFactory>(modelFactory);
services.AddSingleton<IApplicationModelUpdate>(modelFactory);
services.AddScoped<ApplicationModel[]>(provider =>
provider.GetRequiredService<IApplicationModelFactory>().GetModel());
Inject IApplicationModelUpdate into the types that update the model and ApplicationModel[] into the types that use it. This has the advantage that all types resolved for the same request will get a consistent view of the model, even if it changes in the middle of processing that request.
You could also inject IApplicationModelFactory into the consumer code, but I think injecting the model directly is better. Using the factory can lead to different bits of code seeing different models during the same request. The mutability of the model is also an implementation detail that consumer code shouldn't have to worry about.
I wouldn't monkey with dependency injection that way. Instead, inject a factory, and write whatever logic you need to return the proper instance.
Simple factory:
interface IApplicationModelFactory
{
ApplicationModel[] Model { get; }
}
class ApplicationModelFactory : IApplicationModelFactory
{
public ApplicationModel[] Model { get; set; }
}
Registration:
services.AddSingleton<IApplicationModelFactory>
(
new ApplicationModelFactory[] { Model = util.generateApplications() }
)
class receiving the injection:
class Foo
{
protected readonly IApplicationModelFactory _factory;
public Foo(IApplicationModelFactory injected)
{
_factory = injected;
}
protected ApplicationModel[] => _factory.Model;
public void Bar()
{
DoSomethingWithModel(this.ApplicationModel);
}
}
Our existing database deployment has a single 'master' and a read-only replica. Using ASP.NET's Web API2 and an IoC container I want to create controller actions whose attribute (or lack there of) indicate which database connection is to be used for that request (See Controller and Services usage below)...
public MyController : ApiController
{
public MyController(IService1 service1, IService2 service2) { ... }
// this action just needs the read only connection
// so no special attribute is present
public Foo GetFoo(int id)
{
var foo = this.service1.GetFoo(id);
this.service2.GetSubFoo(foo);
return foo;
}
// This attribute indicates a readwrite db connection is needed
[ReadWrteNeeded]
public Foo PostFoo(Foo foo)
{
var newFoo = this.service1.CreateFoo(foo);
return newFoo;
}
}
public Service1 : IService1
{
// The dbSession instance injected here will be
// based off of the action invoked for this request
public Service1(IDbSession dbSession) { ... }
public Foo GetFoo(int id)
{
return this.dbSession.Query<Foo>(...);
}
public Foo CreateFoo(Foo newFoo)
{
this.dbSession.Insert<Foo>(newFoo);
return newFoo;
}
}
I know how to setup my IoC (structuremap or Autofac) to handle per request IDbSession instances.
However, I'm not sure how I would go about making the type of IDbSession instance for the request to key off the indicator attribute (or lack there of) on the matching controller's action. I assume I will need to create an ActionFilter that will look for the indicator attribute and with that information identify, or create, the correct type of IDbSession (read-only or read-write). But how do I make sure that the created IDbSession's lifecycle is managed by the container? You don't inject instances into the container at runtime, that would be silly. I know Filters are created once at startup (making them singleton-ish) so I can't inject a value into the Filter's ctor.
I thought about creating an IDbSessionFactory that would have 'CreateReadOnlyDbSession' and 'CreateReadWriteDbSession' interfaces, but don't I need the IoC container (and its framework) to create the instance otherwise it can't manage its lifecycle (call dispose when the http request is complete).
Thoughts?
PS During development, I have just been creating a ReadWrite connection for every action, but I really want to avoid that long-term. I could also split out the Services methods into separate read-only and read-write classes, but I'd like to avoid that as well as placing GetFoo and WriteFoo in two different Service implementations just seems a bit wonky.
UPDATE:
I started to use Steven's suggestion of making a DbSessionProxy. That worked, but I was really looking for a pure IoC solution. Having to use HttpContext and/or (in my case) Request.Properties just felt a bit dirty to me. So, if I had to get dirty, I might as well go all the way, right?
For IoC I used Structuremap and WebApi.Structuremap. The latter package sets up a nested container per Http Request plus it allows you to inject the current HttpRequestMessage into a Service (this is important). Here's what I did...
IoC Container Setup:
For<IDbSession>().Use(() => DbSession.ReadOnly()).Named("ReadOnly");
For<IDbSession>().Use(() => DbSession.ReadWrite()).Named("ReadWrite");
For<ISampleService>().Use<SampleService>();
DbAccessAttribute (ActionFilter):
public class DbAccessAttribute : ActionFilterAttribute
{
private readonly DbSessionType dbType;
public DbAccessAttribute(DbSessionType dbType)
{
this.dbType = dbType;
}
public override bool AllowMultiple => false;
public override void OnActionExecuting(HttpActionContext actionContext)
{
var container = (IContainer)actionContext.GetService<IContainer>();
var dbSession = this.dbType == DbSessionType.ReadOnly ?
container.GetInstance<IDbSession>("ReadOnly") :
container.GetInstance<IDbSession>("ReadWrite");
// if this is a ReadWrite HttpRequest start an Request long
// database transaction
if (this.dbType == DbSessionType.ReadWrite)
{
dbSession.Begin();
}
actionContext.Request.Properties["DbSession"] = dbSession;
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var dbSession = (IDbSession)actionExecutedContext.Request.Properties["DbSession"];
if (this.dbType == DbSessionType.ReadWrite)
{
// if we are responding with 'success' commit otherwise rollback
if (actionExecutedContext.Response != null &&
actionExecutedContext.Response.IsSuccessStatusCode &&
actionExecutedContext.Exception == null)
{
dbSession.Commit();
}
else
{
dbSession.Rollback();
}
}
}
}
Updated Service1:
public class Service1: IService1
{
private readonly HttpRequestMessage request;
private IDbSession dbSession;
public SampleService(HttpRequestMessage request)
{
// WARNING: Never attempt to access request.Properties[Constants.RequestProperty.DbSession]
// in the ctor, it won't be set yet.
this.request = request;
}
private IDbSession Db => (IDbSession)request.Properties["DbSession"];
public Foo GetFoo(int id)
{
return this.Db.Query<Foo>(...);
}
public Foo CreateFoo(Foo newFoo)
{
this.Db.Insert<Foo>(newFoo);
return newFoo;
}
}
I assume I will need to create an ActionFilter that will look for the indicator attribute and with that information identify, or create, the correct type of IDbSession (read-only or read-write).
With your current design, I would say an ActionFilter is the way to go. I do think however that a different design would serve you better, which is one where business operations are more explicitly modelled behind a generic abstraction, since you can in that case place the attribute in the business operation, and when you explicitly separate read operations from write operations (CQS/CQRS), you might not even need this attribute at all. But I'll consider this out of scope of your question right now, so that means an ActionFilter is the the way to go for you.
But how do I make sure that the created IDbSession's lifecycle is managed by the container?
The trick is let the ActionFilter store information about which database to use in a request-global value. This allows you to create a proxy implementation for IDbSession that is able to switch between a readable and writable implementation internally, based on this setting.
For instance:
public class ReadWriteSwitchableDbSessionProxy : IDbSession
{
private readonly IDbSession reader;
private readonly IDbSession writer;
public ReadWriteSwitchableDbSessionProxy(
IDbSession reader, IDbSession writer) { ... }
// Session operations
public IQueryable<T> Set<T>() => this.CurrentSession.Set<T>();
private IDbSession CurrentSession
{
get
{
var write = (bool)HttpContext.Current.Items["WritableSession"];
return write ? this.writer : this.reader;
}
}
}
I'm using Drum which provides a generic class `UriMaker:
public class UriMaker<TController>
{
// I need use this one
public UriMaker(UriMakerContext context, HttpRequestMessage request) { }
public UriMaker(Func<MethodInfo, RouteEntry> mapper, UrlHelper urlHelper) { }
}
Used like this:
public class UserController : ApiController
{
public UserController(UriMaker<UserController> urlMaker) {}
}
I've used to register it with Unity:
container.RegisterType(typeof(UriMaker<>),
new InjectionConstructor(typeof(UriMakerContext), typeof(HttpRequestMessage)));
but now migrating to Simple Injector. I already have this:
UriMakerContext uriMaker = config.MapHttpAttributeRoutesAndUseUriMaker();
container.RegisterSingle(uriMakerContext);
So how now register UriMaker<> itself?
Although it is possible to configure Simple Injector to allow injecting an UriMaker<TController> directly into your controllers, I strongly advice against this for multiple reasons.
First of all, you should strive to minimize the dependencies your application takes on external libraries. This can easily be done by defining an application specific abstraction (conforming the ISP).
Second, injecting the UriMaker directly makes your extremely hard to test, since the UriMaker is pulled into your test code, while it assumes an active HTTP request and assumes the Web API route system to be configured correctly. These are all things you don't want your test code to be dependent upon.
Last, it makes verifying the object graph harder, since the UriMaker depends on an HttpRequestMessage, which is a runtime value. In general, runtime values should not be injected into the constructors of your services. You should build up your object graph with components (the stuff that contains the application's behavior) and you send runtime data through the object graph after construction.
So instead, I suggest the following abstraction:
public interface IUrlProvider
{
Uri UriFor<TController>(Expression<Action<TController>> action);
}
Now your controllers can depend on this IUrlProvider instead of depending on an external library:
public class UserController : ApiController
{
private readonly IUrlProvider urlProvider;
public UserController(IUrlProvider urlProvider)
{
this.urlProvider = urlProvider;
}
public string Get()
{
this.urlProvider.UriFor<HomeController>(c => c.SomeFancyAction());
}
}
Under the covers you of course still need to call Drum, and for this you need to define a proxy implementation for IUrlProvider:
public class DrumUrlProvider : IUrlProvider
{
private readonly UriMakerContext context;
private readonly Func<HttpRequestMessage> messageProvider;
public DrumUrlProvider(UriMakerContext context,
Func<HttpRequestMessage> messageProvider)
{
this.context = context;
this.messageProvider= messageProvider;
}
public Uri UriFor<TController>(Expression<Action<TController>> action)
{
HttpRequestMessage message = this.messageProvider.Invoke();
var maker = new UriMaker<TController>(this.context, message);
return maker.UriFor(action);
}
}
This implementation can be registered as singleton in the following way:
container.EnableHttpRequestMessageTracking(config);
UriMakerContext uriMakerContext =
config.MapHttpAttributeRoutesAndUseUriMaker();
IUrlProvider drumProvider = new DrumUrlProvider(uriMakerContext,
() => container.GetCurrentHttpRequestMessage());
container.RegisterSingle<IUrlProvider>(drumProvider);
This example uses the Simple Injector Web API integration package to allow retrieving the current request's HttpRequestMessage using the EnableHttpRequestMessageTracking and GetCurrentHttpRequestMessage extension methods as explained here.
I'm creating a class library API that wraps business logic and access to an SQL Server database via Entity Framework 6.
I've designed it using the Unit of work and repository patterns.
The purpose is to make it easy to use and to unit test.
Business logic and validation will be performed in the service layer.
I will not use an IOC container because I feel that it would complicate the API
usage.
The project have 15 repositories and services
The current design is as follows:
Service Layer A -> Unit of work -> Repository A and or B
Service Layer B -> Unit of work -> Repository B and or A...
...
public class ServiceA : IServiceA, IService
{
private readonly IUnitOfWork unitOfWork;
public AssetService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
...
public IList<DomainObjectA> GetAll()
{
return unitOfWork.RepositoryA.GetAll();
}
public void Dispose()
{
unitOfWork.Dispose();
}
...
}
public class UnitOfWork : IUnitOfWork
{
private readonly MyDbContext context = new MyDbContext();
private IRepositoryA repositoryA;
private IRepositoryB repositoryB;
...
public IRepositoryA RepositoryA
{
get { return repositoryA = repositoryA ?? new RepositoryA(context); }
}
public IRepositoryB RepositoryB
{
get { return repositoryB = repositoryB ?? new RepositoryB(context); }
}
...
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class RepositoryA : Repository, IRepositoryA
{
public RepositoryA(MyDbContext context)
: base(context) {}
public IList<DomainObjectA> GetAll()
{
return context.tblA.ToList().Select(x => x.ToDomainObject()).ToList();
}
...
}
Since this is an API that should be used by other projects, I need a nice and "fairly" easy to use interface for the user that consumes the API.
Because of this the UnitOfWork is created in this "public interface" between the user and the service layer, see below.
I also think it's best that the using-statement lies within the API so that the db-context is disposed properly and immediately after each service call.
I started out using the Proxy pattern for this:
Example:
public class ProxyA : Proxy, IServiceA
{
public IList<DomainObjectA> GetAll()
{
using (var service = GetService<ServiceA>())
return service.GetAll();
}
...
}
public abstract class Proxy
{
protected T GetService<T>() where T : IService
{
return (T)Activator.CreateInstance(typeof(T), new object[] { new UnitOfWork()});
}
}
But this would require me to create a proxy for each service. I could of course skip the service interface in the proxy and create a common proxy which handles all the services.
I've also looked at the Facade pattern but can't decide which pattern to use for this particular scenario.
My questions:
Is this a good approach or are there any other design patterns that will solve this problem?
Also, should there be one public API entry point or several, grouped by some business logic?
I see nothing wrong with your design and the patterns you use.
Regarding the proxy pattern it is your call if you want to use it or not. As you mention you have to create boiler plate code to create one for every service. If it is arguable if you want to use it only to hide the call to the db service, or you prefer to add that line of code every time you call the service (and make sure you do it to avoid leaks). Also you may consider if you may need to add extra functionality in the Proxy in the future, which will put extra weight to create the proxy option.
Regarding a single entry point or several, I would create a ServiceA, ServiceB, ServiceC etc (so several) grouped for business logic domains. Typically you'll have between 5-20 (just an approximate number to give an idea of the magnitude)
You may want to review the interface segregation principle which supports this idea
http://en.wikipedia.org/wiki/Interface_segregation_principle
When using Ninject with mvc3 we do something like, install ninject, registerger modules-or-services .
We write control like this
public class HomeController : Controller
{
private IHelloService _service;
public HomeController(IHelloService service)
{
_service = service;
}
public string Index()
{
return _service.GetGreeting();
}
}
I want to do something like
public class HomeController : Controller
{
private IHelloService _service;
/*
No default constructor
*/
public string Index()
{
_service= Ask_Ninject_to_provide_resource
return _service.GetGreeting();
}
}
Your current practice of writing controls is better than what you are proposing. You want to be able to inject through fields, rather than constructor. This is a bad idea and it's not recommended.
Quote from Ninject wiki:
"Although its simplicity is tempting, you should generally try to avoid using field injection, since the value can then only be set via Ninject. This makes unit testing much more complex, since sometimes it's easiest to use dependency injection by hand to inject mock objects into your unit tests. (Unit testing with Ninject is covered in more depth later.)"
Alternative is to inject through properties, but once again, you have to have a very good reason to do so. Most of the time constructor injection should do the job.
public class HomeController : Controller
{
private IHelloService _service;
/*
No default constructor
*/
public string Index()
{
_service= DependencyResolver.Current.GetService<IHelloService>();
return _service.GetGreeting();
}
}
Though I would seriously question the need to do this.