preload and cache data in a Web API OWIN application - asp.net-web-api2

I'm building a Web API application using OWIN and hosting in IIS. I now want to preload some data from a database which can be used in the controller methods without loading the data from the database for each request. I have also followed this guide to setup Windsor as IoC container. Does anyone know how to properly set this up?

It's easy to do. In the Startup class, populate one or more classes with the database data. Do this as you would normally load data into a data store.
Register each of these classes with your IoC from the Startup class. It is best to separate the controller from data layer, so create a business logic layer or a repository layer that takes your data store class in the constructor like this:
public class Service
{
private readonly IDataStore _dataStore;
public Service(IDataStore dataStore)
{
_dataStore = dataStore;
}
}
Register the service with your IoC and you should be good to go.
Hope that helps.

Related

How to keep DbContext and entities internal while injecting into services?

I am creating an ASP Core MVC application. Within my solution I have Web project (MVC) and a Core project (BLL/DAL).
I thought it would be a good idea to keep my persistence models and DbContext inside Core project as internal, since Web project should never need the persistence models or need to access context directly, it will get all it needs from services.
Core project has an IServiceCollection extension method which allows me to add the DbContext from service layer to the service container in MVC project without MVC needing direct access to it.
The issue comes when I need to use the DbContext inside my service classes in Core project. The service classes must be public for the view layer to access them, but I cannot inject DbContext into them via the constructor because it is internal.
If I want to make the DbContext public so it can be injected, I must also make all of my persistence models public since they are declared with DbSets in the context.
Do I really need to make all of my persistence models public or is there a way to resolve this?
First of all, you need to make Entity public, otherwise, you will not be able to access them in Service Layer. We should reference Entity from Data Access Layer instead of accessing ViewModel from Service Layer in Data Access Layer. And then, you could make DbContext public to be able accessed from Service Layer.
If you want to avoid accessing DbContext directly from Service Layer, you could consider implementing public Repository which will inject DbContext to handle CURD operations.

What is the purpose to create Application and Loader in Lagom

I am reading following tutorial on Lagom.
I understand DI but the section also talks of Application and Loader. I am unable to understand the purpose of creating an Application and Loader class. So far, I have been able to run basic services (e.g., hello, world service from GettingStarted) without creating Application and loader class.
Let us consider a sample ApplicationLoader (and this is not the only way to do but an example for the sake of the question)
abstract class FriendModule (context: LagomApplicationContext)
extends LagomApplication(context)
with AhcWSComponents
with CassandraPersistenceComponents
{
persistentEntityRegistry.register(wire[FriendEntity])
override def jsonSerializerRegistry = FriendSerializerRegistry
override lazy val lagomServer: LagomServer = serverFor[FriendService](wire[FriendServiceImpl])
}
class FriendApplicationLoader extends LagomApplicationLoader {
override def load(context: LagomApplicationContext): LagomApplication =
new FriendModule(context) with ConductRApplicationComponents
override def loadDevMode(context: LagomApplicationContext): LagomApplication =
new FriendModule(context) with LagomDevModeComponents
override def describeService = Some(readDescriptor[FriendService])
}
Firstly the reason we create a class FriendModule that extends `LagomApplication, is to mixin all our dependencies. They could be:
If the application relies on cassandra and persistence api, then we mixin that. If the application needs to make HTTP calls then we provide it the WSClient etc
We of-course wire in the compile time dependencies
By doing below, we bind the implementation with the service declared
override lazy val lagomServer: LagomServer = serverForFriendService
But notice, we haven't still coupled our microservice with a Service Locator.
The role of a service locator is to provide the ability to discover application services and communicate with them. For example: If an application has five different microservices running, then each one would need to know the address of every other for the communication to be possible.
Service Locator takes this responsibility of keeping information of the address of the microservices concerned. In the absence of this service locator, we would need to configure the URL of each microservice and make it available to each microservice (may be via a properties file?).
So in the class FriendApplicationLoader we bind our implementation with LagomDevModeComponents in the dev case. LagomDevModeComponentsregisters our service with the registry. This is how magically Lagom microservices can communicate with others in a simple manner.

webapi aspnet 4 Architecture

I've project using Entity Framework 5 Code First, WebApi, ASPNET MVC 4, Repository and Unit of Work pattern, etc.
My architecture is as follows:
One project for the POCOS
One project with the context, Repository, Unit Of Work, etc
One project with the contracts (IRepository, IUnitOfWork, etc)
One WebApi project which holds ApiControllers for each entity of the model (GET, POST, PUT, DELETE).
Now, if I don't want to use SPA (as I don't have time right now to learn it) and I want to do something quick, What should I do? a new ASPNET MVC 4 project with Controllers inheriting from Controller rather than ApiController, and those controllers consuming the WebApi controllers?
Like this?
public ActionResult Index()
{
return View(WebApiProj.Uow.Houses.GetAll());
}
That doesn't seems to be quite good as it should be creating a Get pointing to the WebApi controller in the other project.
I'm thinking about this architecture, because mobile clients, web clients and any other clients would be calling the same services which sounds good.
Any advices on this architecture? Pros or cons?
I am not sure if what you show is possible? WebApiProj.Uow.Houses.GetAll() Is treating Houses as if it was a class with a static GetAll function on it. Houses is an instance class that needs to be instantiated per request and may/should have constructor injection concerns to handle too... GetAll would normally be an instance method.
Given you are in a situation where you are going to have multiple code clients i.e. the WebApi controllers and the MVC controllers you should consider adding a Service Layer to your project. http://martinfowler.com/eaaCatalog/serviceLayer.html.
Your Service Layer will probably take the form of a single class (if this is a small ish project but split it up if needed), it will have the Repositories and the Infrastructure code injected. You should end up with a series of CRUD and UseCase sounding method names that contain the orchestration logic between repositories, factories and unit of work classes.
public interface IMyServiceLayerClass
{
IEnumerable<House> GetAllHouses();
House SaveHouse(House house);
IEnumerable<Windows> GetAllHouseWindows(int houseId);
//etc
}
public class MyServiceLayerClass : IMyServiceLayerClass
{
private readonly IRepository<House> _houseRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IRepositoryTypeB _repositoryTypeB;
Public MyServiceLayerClass(IUnitOfWork unitofwork, IRepository<House> houseRepository, IRepositoryTypeB repositoryTypeB)
{
//Populate the private readonly's
}
public IEnumerable<House> GetAllHouses()
{
return _houseRepository.GetAll();
}
Your two types of controller can then accept the Service class and have very thin logic just to forward on to the service layer.
public class HomeController : Controller
{
private readonly IMyServiceLayerClass _myServiceLayerClass;
public HomeController(IMyServiceLayerClass myServiceLayerClass)
{
_myServiceLayerClass= myServiceLayerClass;
}
public ViewResult Index()
{
return View(_myServiceLayerClass.GetAllHouses());
}
Same for the Api:
public class HouseController : ApiController
{
private readonly IMyServiceLayerClass _myServiceLayerClass;
public HouseController (IMyServiceLayerClass myServiceLayerClass)
{
_myServiceLayerClass= myServiceLayerClass;
}
public IEnumerable<House> Get()
{
return _myServiceLayerClass.GetAllHouses();
}
This will allow you to reuse the same business logic and orchestration across the controllers abstract the logic away from your WebApi and Mvc applications.
This code could easily live in your project that defines the contracts as it is only dependent upon interfaces. Or you could add its interface into contracts too and then create another project class Domain or Service which can hold the implementation of the service class.
I would strongly suggest you leave you Controllers to do what they do best and let them handle the delegation of the UI specific elements and re-factor non UI specific logic into a reusable service layer. This would allow Unit tests for controllers to focus on testing for the correct action result and status codes etc and allow your domain logic to be tested independently.
Take a look at my answer for another architecture question on MVC. The key for your question is to have an application or domain layer that both the MVC Controller and Web API Controllers can use to access the business model (The M in MVC). You do not want to call the Web API directly from the MVC Controller as it has overhead for serialization and de-serialization that is not required here. Instead call the application/domain layer directly.

MVC Controllers WCF Service

I am using ASP.net MVC3 for my presentation layer and my data access and business logic are exposed through a WCF Service. Should my controllers call the WCF service or should there be a further level of abstraction such as a repository which calls the WCF service.
Repository which calls the service
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public ProductRepository(ProductServiceClient client)
{
_client = client;
}
Service directly in the controllers
public ProductController(ProductServiceClient client)
{
_client = client;
}
The repository classes do nothing apart from call the methods exposed via the service.
Sorry I am well confused about your question, but I am sorry if I have misunderstood. Hope my pointers will clear this up.
Repositories related to persistence and define a way to handle the
infrastructure layer i.e. dealing with data (in memory repository,
sql repository or generic one)
Services if you like use these repositories to perform the
contractual operations such as getting the client in your case.
Services are called by clients or someone that requests services and
service in turn calls the repository which in turn calls the data
operations.
So you may need to change your wcf to work with repositories and let your controller call services..hope that helps
I would start by doing the exact oposite - the WCF should call methods inside the repository.
The data layer should be universal, and should be able to be accessed through any means (wcf should be one, mvc website should be another, etc).
That way you can also unit test your projects, and it's easier to keep track of it. Wcf should be considered as an extra api to your program in this case.
I am more concerned of where the business rules should be stored, but I would vote for mvc controllers for business logic, and wcf services invoking those internally.

Using MEF in Service layer (WCF)

So far I found that MEF is going well with presentation layer with following benefits.
a. DI (Dependency Injection)
b. Third party extensibility (Note that all parties involved should use MEF or need wrappers)
c. Auto discovery of Parts (Extensions)
d. MEF allows tagging extensions with additional metadata which facilitates rich querying and filtering
e. Can be used to resolve Versioning issues together with “DLR and c# dynamic references” or “type embedding”
Pls correct me if I’m wrong.
I'm doing the research on whether to use MEF in Service layer with WCF. Pls share your experience using these two together and how MEF is helping you?
Thanks,
Nils
Update
Here is what my result of research so far. Thanks to Matthew for helping in it.
MEF for the Core Services - cost of changes are not justifying the benefits. Also this is big decision and may affect the service layer in good or bad way so needs lot of study. MEF V2 (Waiting for stable version) might be better in this case but little worried about using MEF V1 here.
MEF for the Function service performs - MEF might add the value but it’s very specific to the service function. We need to go deep into requirement of service to take that decision.
Study is ongoing process, so everyone please share your thoughts and experience.
I think any situation that would benefit from separation-of-concerns, would benefit from IoC. The problem you face here is how you require MEF to be used within your service. Would it be for the core service itself, or some function the service performs.
As an example, if you want to inject services into your WCF services, you could use something similar to the MEF for WCF example on CodePlex. I haven't looked too much into it, but essentially it wraps the service location via an IInstanceProvider, allowing you to customise how your service type is created. Not sure if it supports constructor injection (which would be my preference) though...?
If the WCF service component isn't where you want to use MEF, you can still take advantage of MEF for creating subsets of components used by the service. Recently for the company I work for, we've been rebuilding our Quotation process, and I've built a flexible workflow calculation model, whereby the workflow units are MEF composed parts which can be plugged in where needed. The important part here would be managing how your CompositionContainer is used in relation to the lifetime of your WCF service (e.g. Singleton behaviour, etc.). This is quite important if you decide to create a new container each time (container creation is quite cheap, whereas catalog creation can be expensive).
Hope that helps.
I'm working on a solution where the MEF parts that I want to use across WCF calls are stored in a singleton at the application level. This is all hosted in IIS. The services are decorated to be compatible with asp.net.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
In Global.asax, I import the parts.
[ImportMany(typeof(IOption))]
public IEnumerable<IOption> AvailableOptions{ get; set; }
After initializing the catalog and container, I copy the imported objects to my singleton class.
container.ComposeParts(this);
foreach (var option in AvailableOptions)
OptionRegistry.AddOption(option);
EDIT:
My registry class:
public static class OptionRegistry
{
private static List<IOption> _availableOptions= new List<IOption>();
public static void AddOption(IOption option)
{
if(!_availableOptions.Contains(option))
_availableOptions.Add(option);
}
public static List<IOption> GetOptions()
{
return _availableOptions;
}
}
This works but I want to make it thread safe so I'll post that version once it's done.
Thread-safe Registry:
public sealed class OptionRegistry
{
private List<IOptionDescription> _availableOptions;
static readonly OptionRegistry _instance = new OptionRegistry();
public static OptionRegistry Instance
{
get { return _instance; }
}
private OptionRegistry()
{
_availableOptions = new List<IOptionDescription>();
}
public void AddOption(IOptionDescription option)
{
lock(_availableOptions)
{
if(!_availableOptions.Contains(option))
_availableOptions.Add(option);
}
}
public List<IOptionDescription> GetOptions()
{
return _availableOptions;
}
}
A little while ago i was wondering how I could create a WCF web service that will get all of its dependencies wired by MEF but that i wouldnt need to write a single line of that wire up code inside my service class.
I also wanted it to be completely configuration based so i could just take my generic solution to the next project without having to make code changes.
Another requirement i had was that i should be able to unit-test the service and mock out its different dependencies in an easy way.
I came up with a solution that ive blogged about here: Unit Testing, WCF and MEF
Hopefully will help people trying to do the same thing.