Mono or Flux request body in WebFlux controller - spring-webflux

What is the difference between a controller that gets input regular java payload and that of reactive payload? For example, say I have the following 2 endpoints:
#RestController
public class MyController {
#PostMapping
public Flux<SomeObject> doThing(#RequestBody MyPayload playlod) {
// do things that return flux - reactive all the way from this controller
and this one:
#RestController
public class MyController {
#PostMapping
public Flux<SomeObject> doThing(#RequestBody Mono<MyPayload> playlod) {
I don't understand the difference between the 2 methods in reactive point of view.

According to WebFlux documentation:
The request body can be one of the following way and it will be decoded automatically in both the annotation and the functional programming models:
Account account — the account is deserialized without blocking
before the controller is invoked.
Mono<Account> account — the
controller can use the Mono to declare logic to be executed after the
account is deserialized.
Flux<Account> accounts — input streaming
scenario.

Related

Injecting controller in service

Is this doable in ASP.NET Core? I want to move existing HomeContoroller logic to IHomeService, but there're action logic, where they call some base controller methods that are difficult to do without controller, so I thought moving action logic to this service and use DI to get the current controller instance in there. Or maybe there's a better approach?
public class HomeController : ControllerBase
{
public MyController(IHomeService service)
{
}
}
public class HomeService : IHomeService
{
public HomeService(ControllerBase controller, IOtherService otherService)
{
}
}
There are two problems with your approach:
HomeService accepts a ControllerBase instance. Since all controller classes inherit from ControllerBase. While you could map a specific type to ControllerBase in your DI system, this would not be very useful.
You are introducing a chicken or the egg problem with the circular dependency on ControllerBase:
HomeController depends on HomeService and
HomeService depends on having a controller (most probably HomeController)
To break the cycle you could remove controller from the constructor of HomeService and pass it as parameter to those methods of IHomeService that need access controller.
Another approach would be to change controller to a property and wire up instances in the constructor:
public class HomeController
{
public HomeController(IHomeService homeService)
{
// Assign controller to service here:
homeService.Controller = this;
}
}
I would recommend to use the method parameter approach, so the compiler forces you to pass controller where it is needed.

Controlling lifetime of objects created by factory generated by ToFactory()

I am using the following Ninject related nuget packages in an MVC 5 WebAPI application:
Ninject.MVC5
Ninject.Extensions.Factory
ninject.extensions.conventions
I have a simple repository and a corresponding factory class like so:
public interface ITaskRunner
{
void Run();
}
public interface IRepository<T> where T: class
{
T[] GetAll();
}
public interface IRepositoryFactory<T> where T: class
{
IRepository<T> CreateRepository();
}
I have setup the Ninject bindings using ToFactory() from Ninject.Extensions.Factory like so:
kernel.Bind<ITaskRunner>().To<TaskRunner>().InSingletonScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
kernel.Bind<IRepositoryFactory<Contact>>().ToFactory();
I am using the factory in the following class:
public class TaskRunner : ITaskRunner
{
//MyTask is a simple POCO class(not shown for brevity)
IRepositoryFactory<MyTask> repoFactory = null;
IRepository<MyTask> repo = null;
public TaskRunner(IRepositoryFactory<MyTask> repoFactory)
{
this.repoFactory = repoFactory;
repo = repoFactory.CreateRepository();
}
//implementation elided
}
I am noticing that the call to repoFactory.CreateRepository() always returns the same instance of the factory (dynamic proxy) that Ninject generates.
Question : Is there a way to change/control this behavior and set a "lifetime" such as Transient, PerThread etc. for the instance that "CreateRepository" returns?
In this particular case, tasks might be processed asynchronously on multiple threads and the repository is not thread safe and hence singleton behavior for the instance returned from "CreateRepository" is not desirable.
I'm not sure what you are trying to achieve, but results you are seeing are quite expected because your TaskRunner is bound as Singleton (so constructed once), and you retrieve your repository in the TaskRunner constructor, which again happens once, and so repo is always the same instance. Note this happens regardless of how you bind IRepository and IRepositoryFactory, see Captive Dependency post by Mark Seemann for details http://blog.ploeh.dk/2014/06/02/captive-dependency/.
In fact, if you need to create repo in the constructor, you could just inject IRepository itself. The power of the Factory extension lies in the fact that it allows to resolve instances at runtime, not construction time. For example, if your TaskRunner has Run() method, you can create repository in it, so each task to run can have its own instance.

Register WCF proxy wrapper using Unity

I am trying to consume WCF in my MVC web app. I have implemented the channel factory for instantiating the proxy client.
I am stuck at a point. Here is the code highlight -
I created a proxy base class where i am creating the channel :
public abstract class ServiceProxyBase<T> : IDisposable where T : class
For creating teh proxy wrapper class i have inherited this base class as :
public class ProxyWrapper : ServiceProxyBase<IMyService>,IMyService
Here "IMyService" is the WCf contract.
Now, in the controllers i have added overloaded constructors as :
public class AccountController : Controller
{
private IMyService businessService;
public AccountController(IMyService _businessService)
{
this.businessService = _businessService;
}
}
For injecting dependency I have included unity.mvc4 package.
It works fine when I am using the following code :
container.RegisterType<IMyService, ProxyWrapper>();
This works as long as the ProxyWrapper is inheriting the IMyService interface directly. If i remove the inheritance like
public class ProxyWrapper : ServiceProxyBase<IMyService>
it gives an error while registering type.
I would like to have a way without inherting the contract in the proxy wrapper. I have spent almost a day trying to fix this. But am able to figure out a solution.
Please give your valuable suggestions on this.
If I understand correctly, your application is using a WCF service but the functionality your application needs is limited compared to the functionality that the service offers (it contains more methods than you need). According to the Interface Segregation Principle, "no client should be forced to depend on methods it does not use" and the Dependency Inversion Principle states that clients own the abstraction.
In other words, you should define your own interface that the application should use and define an implementation that wraps (i.e. composition over inheritance) the generated WCF proxy class.
For instance:
public interface IMyApplicationService
{
object GetStuff();
void PutStuff(object instance);
}
public class MyServiceApplicationProxy : IMyApplicationService
{
private readonly ProxyWrapper wcfProxy;
public MyServiceApplicationProxy(ProxyWrapper wcfProxy) {
this.wcfProxy = wcfProxy;
}
public object GetStuff() {
return this.wcfProxy.GetStuff();
}
public void PutStuff(object instance) {
this.wcfProxy.PutStuff(instance);
}
}
To make application development easier, makes your code easier to read, maintain and test.
You might even want to change the methods of your interface to better suit your application needs. Remember: the client defines the interface! So that might mean that you need to do more mapping inside the MyServiceApplicationProxy class to map adapt your core domain to the contract of the external web service. Don't let the external WCF service's contract leak into your core domain.

How do access the HttpServerUtility in a WebAPI controller (MVC 4)

I need to access the Server.MapPath(virtualPath) method in a controller in an MVC 4 ApiController.
The answer is usually to access it from ControllerContext.HttpContext.Server. However, unlike MvcControllers, the ControlerContext for an ApiController has no HttpContext.
The WebApiAppication that is instantiated in Global.asax.cs has an HttpContext element (Context). However, unlike MVC 3 and earlier, I can't find a way to access the WebApiApplication from a controller. (Earlier generations stored a reference to it in a static Instance variable. MVC 4 removes that.)
Also, I'm trying to find something that will also work without a ton of extra scaffolding when I call the controller methods from a unit Test. I think I could access it, even in a WebApi Controller, using HttpContext.Current (at least it compiles), but I can't mock that for testing. (I'm talking unit testing here, where you call directly to the Controller methods. I've seen some recent tutorials where you unit test with a thin HttpClient, and thus test the whole stack. That seems more like low-level integration testing to me.)
This doesn't seem like it should be that difficult, but I've spent several hours googling it and trying things, and my head's getting bloody from beating it against the wall.
I'd recommend you abstracting this functionality:
public interface IMyDependency
{
string MapPath(string path);
}
and then have an implementation:
public class MyConcreteDependency: IMyDependency
{
public string MapPath(string path)
{
return HostingEnvironment.MapPath(path);
}
}
and finally your ApiController is completely independent on all static method calls making it unit test friendly:
public class MyController: ApiController
{
private readonly IMyDependency dependency;
public MyController(IMyDependency dependency)
{
this.dependency = dependency;
}
public HttpResponseMessage Get()
{
var path = this.dependency.MapPath("~/App_Data");
...
}
}
For ApiControllers, build yourself a DelegatingHandler and push all of your goodies onto request.Properties. You can then retrieve them from your request whether you are testing or running live. The benefit is that you then have zero dependency on Session in your Controller.
MessageHandler
public class ContextHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
// get the goodies to add onto the request
var goodies = /* call to goodieGoodieYumYum */
// add our goodies onto the request
request.Properties.Add(Constants.RequestKey_Goodies, goodies);
// pass along to the next handler
return base.SendAsync(request, cancellationToken);
}
}
Controller Action
var goodies = (List<Goodie>)Request.Properties[Constants.RequestKey_Goodies];

Model-Service decoupling: what if my model needs a service?

The Service layer is supposed to be on top of the Model layer. As such, models are not supposed to call services.
However, I'm facing a situation where I need to, for example:
interface Component {
getResult();
}
class Number implements Component {
private value;
public getResult() {
return value;
}
}
class Addition implements Component {
private component1;
private component2;
public getResult() {
return component1->getResult() + component2->getResult();
}
}
class ConstantFromExternalSource implements Component {
private identifier;
public getResult() {
// call a service for fetching constant identified by identifier
}
}
(pseudo-code)
Here, my model needs to access an external data source through a Service (webservice or not).
How am I supposed to do in this situation? Is it OK to call a service in the model?
If you suggest to move away the "getResult" method from the model and put it into the "ComponentService", I would disagree because I would then loose all the advantages of OOP (and here my model makes a tree that needs to be recursively resolved, so OOP is the best solution).
You can achieve this in several ways.
First of all you can extract your model's dependency in separate interface like:
interface CustomService {
getResult();
}
class ExternalService implments CustomService
{
getResult() { // access web service }
}
And then inject that dependency into the model:
class ConstantFromExternalSource implements Component {
private identifier;
private CustomService service;
ConstantFromExternalSource(CustomService service)
{
this.service = service;
}
public getResult() {
// call a service for fetching constant identified by identifier
return service.getResult();
}
}
Another way to achieve this is to use Observer Design Pattern and notify higher level abstractions that you need something from them.
In both ways you can decouple you model from concrete implementation of the service layer.
I would have the external source return directly the constant as a Component. I wouldn't couple the ConstantFromExtenralSource class to a service, not even as the interface, because the class (at least in this form) does nothing but call the service.
However if the external source returns some data that needs to be wrapped up in the ConstrantFromExternalSource class, I'd just push the data into the object via the constructor.
In a nutshell, if the model is just an abastraction to get data from an external source, just use a Repository to actulally get the data and to return a model if the external source won't return directly the object you need.
Is it OK to call a service in the model?
Depends on what kind of service. As far as DDD goes,
The domain should definitely not know about the underlying application layer services that consume the domain.
Domain layer services are not much of a problem since they are part of the same layer.
In contrast, Infrastructure layer services have to be injected into your domain objects and their interfaces must be declared in the domain layer if you want loose coupling between domain and infrastructure (same as with repository interfaces/implementations). Sergey has a good implementation of this.