How to access Request.Properties outside of Web API Controller - vb.net

I'm setting a Property on Request.Properties inside a DelegatingHandler after I pluck some data out of a header on an incoming request to a Web API.
This all works fine. I can also access Request.Properties from within the controller as well as in my Action and Exception filters. However, I also need to access this data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places,
I can see HttpContext.Current from this class, and I can see the original header from here, so I guess I could pluck it out again, but since I have already done this and put it in the Properties it seems to make more sense to get it from there. However, I don't seem to have access to the Request.Properties from anywhere else.
If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?

I also need to access [Request.Properties] data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places... However, I don't seem to have access to the Request.Properties from anywhere else. If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?
You can get it from HttpContext.Current, though it is less than ideal. Keep in mind that if any other non-web applications consume the same business layer, then HttpContext.Current would be null. HttpContext.Current is only non-null when you are running in IIS, and an IIS thread is handling the execution of the request stack. If you ever plan to self-host the web api using OWIN without IIS, there will be no HttpContext.Current.
Personally, if the data really is important enough to be passed into the business layer to be logged, then I would just pass it to the business layer method:
public Task<HttpResponseMessage> SomeAction(SomeModel model) {
... other code
someBusinessLayerObject.SomeMethod(arg1, arg2, Request.Properties["myHeaderKey"]);
}
...If you need other values from Request.Properties, then you can just pass the whole dictionary to the methods that will end up using its values.
A third option if you are using an inversion of control container would be to add some kind of scoped object dependency class and put the data in there. Then constructor inject it into your business layer class:
public interface IHaveRequestData {
IDictionary<string, object> Properties { get; set; }
}
public class RequestData : IHaveRequestData {
public IDictionary<string, object> Properties { get; set; }
}
// ioc registration pseudocode
iocContainer.Register<IHaveRequestData, RequestData>(Lifetime
.WhateverYouNeedSoThatOneOfTheseGetsCreatedForEachWebRequest);
public class SomeController : ApiController {
private readonly IHaveRequestData RequestData;
public SomeController(IHaveRequestData requestData) {
RequestData = requestData;
}
public Task<HttpResponseMessage> SomeAction() {
// you may even be able to do this part in an action filter
RequestData.Properties = Request.Properties;
}
}
public class SomeBusinessLayerComponent {
private readonly IHaveRequestData RequestData;
private readonly ILog Log;
public SomeBusinessLayerComponent(IHaveRequestData requestData, ILog log) {
RequestData = requestData;
Log = log;
}
public Task SomeMethod() {
Log.Info(RequestData["myHeader"]);
}
}

Related

How to make a Dictionary accessible from all controllers in a .Net 5 API?

I have a Dictionary that will be populated with data from the database at startup, with a method that takes the key as a parameter, and returns the value. How to make the dictionary publicly accessible to all controllers? After searching, I learned that I would need to use Dependency Injection, but I'm failing at implementing it. Any resource that can get me on track is highly appreciated.
There are many ways to implement your question with/without DI. One of which is to write a static class that will be filled upon app startup.
No dependency injection:
Declare a static class that contains your dictionary. By being static there would only be 1 instance on app start.
public static class StaticDictionary {
public Dictionary<string,int> MyDictionary {get;set;}
}
In your Startup.cs - Configure method, append your db context in the parameters.
public void Configure(..., YourDbContext dbContext)
In the Configure method again, append your code that fills the dictionary.
public void Configure(..., YourDbContext dbContext){
...
// no need to modify the code above this, just append the fill dictionary code
foreach(var item in dbContext.TableName.ToList()){
StaticDictionary.MyDictionary.Add(...);
}
}
In your controllers, you could access StaticDictionary without DI.
public IActionResult Index{
var something = StaticDictionary.MyDictionary["Something"];
return View();
}

netcore 2.1 Distributed cache with Scoped repository

Need some help.
I have a .netcore 2.1 API which is secured via Azure Bearer token from its clients. I am wanting to collect user information from the bearer token of clients and store it in a SQL database so that I can tag entries within the database if they are being added/deleted/edited etc. For the SQL table joins I therefore need the user imformation in SQL.
Below is my implementation of a Cache Service using IDistributedCache. On Init I am trying to load all currently stored users from the SQL DB in to the cache, then added to it when new users connect in.
To capture the connections across the entire API I was using a TypeFilterAttribute to execute OnActionExecuting.
The problem is that the CacheService is a singleton and is calling the UserRepository - which is scoped. This isn't allowed.
Any thoughts?
startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
// Context
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<CacheService>();
// Repositories
services.TryAddScoped<IUserRepository, UserRepository>();
services.AddDistributedMemoryCache();
services.AddMvc(
opts => opts.Filters.Add(new HttpInterceptor())
)
...
CacheService.cs
public class CacheService
{
private readonly IDistributedCache _cache;
private readonly IUserRepository _userRepository;
public CacheService(
IDistributedCache cache,
[FromServices] IUserRepository userRepository
)
{
_cache = cache;
_userRepository = userRepository;
// Populate cache from DB
var users = _userRepository.GetAll().Result;
foreach (var u in users)
{
if (_cache.GetAsync(u.Username).Result == null)
{
var profileSerialised = JsonConvert.SerializeObject(UserToUserProfile(u));
var entry = Encoding.UTF8.GetBytes(profileSerialised);
_cache.SetAsync(u.Username, entry, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) });
}
}
}
HttpInterceptor.cs
public class HttpInterceptor : TypeFilterAttribute
{
public HttpInterceptor() : base(typeof(IHttpInterceptor))
{
}
private class IHttpInterceptor : IActionFilter
{
private readonly CacheService _cache;
private readonly IUserRepository _userRepository;
public IHttpInterceptor(
CacheService cache,
IUserRepository userRepository)
{
_cache = cache;
_userRepository = userRepository;
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated)
{
this._cache.GetUserProfile(context.HttpContext.User.Identity.Name);
}
}
First, you're looking at this upside-down and backwards. Having some service add stuff to the cache and then having other code just assume that stuff is in the cache ready to go is a recipe for disaster. Instead, have your dependent code literally request the data it needs, and then, if you want to cache it, do it the method that fetches the data. That way your app code remains agnostic about where the data is coming from; it just calls a method and it gets the data it wants. Under the hood, it's either pulled from the database or the cache, depending on which is available/preferred.
Your cache service has serious issues anyways. First, it should not be a singleton in the first place. There's no reason for it to be, and since you're dealing with scoped services inside, you're only making things more difficult than they need to be. Second, you should never ever utilize I/O in a constructor. Only simple variable/prop initialization should be done there. Anything that requires actual work should go into a method. If you truly want to do something on initialization, then you should implement a factory pattern. For example, you might have something like a CacheServiceFactory with a Create method that returns a fully instantiated CacheService including calling any methods that do actual work.
With the disclaimers aside, in general, to use a scoped service in a singleton, you must create a scope. This must be done every time you want to utilize the service; you cannot persist the service to an ivar on your singleton class. Simply, you inject IServiceProvider into your class, which is itself singleton-scoped, so you'll have no problems with that. Then, when you need to utilize a scoped service:
using (var scope = provider.CreateScope())
{
var repo = scope.ServiceProvider.GetRequiredService<IUserRepository>();
// do something with repo
}
This is called the service locator anti-pattern. It's called such because it's something you should really avoid doing. Sometimes that's no always possible. However, more often than not, you can simply design things in a different way: such as making the service scoped itself.

Autofac.Multitenant in an aspnet core application does not seem to resolve tenant scoped dependencies correctly

I'm in the process of upgrading a Multitenant dotnet core solution which utilises the Autofac.Multitenant framework. I'm not having a lot of luck getting tenancy resolution working correctly. I've created a simple demonstration of the problem here: https://github.com/SaltyDH/AutofacMultitenancy1
This repo demonstrates registering a InstancePerTenant scoped dependency TestMultitenancyContext which is resolved in the Home Controller. Due to issues with using IHttpContextAccessor, I'm using a custom RequestMiddleware class to capture the current HttpContext object so that I can perform logic on the current HttpContext request object in the MultitenantIdentificationStrategy.
Finally, TestFixture provides a simple xUnit test which, at least on my machine returns "tenant1" for both tenants.
Is there something I've missed here or is this just not currently working?
UPDATE 10/6/2017: We released Autofac.AspNetCore.Multitenant to wrap up the solution to this in a more easy to consume package. I'll leave the original answer/explanation here for posterity, but if you're hitting this you can go grab that package and move on.
I think you're running into a timing issue.
If you pop open the debugger on the HttpContext in the middleware you can see that there's a RequestServicesFeature object on a property called ServiceProvidersFeature. That's what's responsible for creating the per-request scope. The scope gets created the first time it's accessed.
It appears that the order goes roughly like this:
The WebHostBuilder adds a startup filter to enable request services to be added to the pipeline.
The startup filter, AutoRequestServicesStartupFilter, adds middleware to the very beginning of the pipeline to trigger the creation of request services.
The middleware that gets added, RequestServicesContainerMiddleware, basically just invokes the RequestServices property from the ServiceProvidersFeature to trigger creation of the per-request lifetime scope. However, in its constructor is where it gets the IServiceScopeFactory that it uses to create the request scope, which isn't so great because it'll be created from the root container before a tenant can be established.
All that yields a situation where the per-request scope has already been determined to be for the default tenant and you can't really change it.
To work around this, you need to set up request services yourself such that they account for multitenancy.
It sounds worse than it is.
First, we need a reference to the application container. We need the ability to resolve something from application-level services rather than request services. I did that by adding a static property to your Startup class and keeping the container there.
public static IContainer ApplicationContainer { get; private set; }
Next, we're going to change your middleware to look more like the RequestServicesContainerMiddleware. You need to set the HttpContext first so your tenant ID strategy works. After that, you can get an IServiceScopeFactory and follow the same pattern they do in RequestServicesContainerMiddleware.
public class RequestMiddleware
{
private static readonly AsyncLocal<HttpContext> _context = new AsyncLocal<HttpContext>();
private readonly RequestDelegate _next;
public RequestMiddleware(RequestDelegate next)
{
this._next = next;
}
public static HttpContext Context => _context.Value;
public async Task Invoke(HttpContext context)
{
_context.Value = context;
var existingFeature = context.Features.Get<IServiceProvidersFeature>();
using (var feature = new RequestServicesFeature(Startup.ApplicationContainer.Resolve<IServiceScopeFactory>()))
{
try
{
context.Features.Set<IServiceProvidersFeature>(feature);
await this._next.Invoke(context);
}
finally
{
context.Features.Set(existingFeature);
_context.Value = null;
}
}
}
}
Now you need a startup filter to get your middleware in there. You need a startup filter because otherwise the RequestServicesContainerMiddleware will run too early in the pipeline and things will already start resolving from the wrong tenant scope.
public class RequestStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
builder.UseMiddleware<RequestMiddleware>();
next(builder);
};
}
}
Add the startup filter to the very start of the services collection. You need your startup filter to run before AutoRequestServicesStartupFilter.
The ConfigureServices ends up looking like this:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.Insert(0, new ServiceDescriptor(typeof(IStartupFilter), typeof(RequestStartupFilter), ServiceLifetime.Transient));
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterType<TestMultitenancyContext>().InstancePerTenant();
builder.Populate(services);
var container = new MultitenantContainer(new MultitenantIdentificationStrategy(), builder.Build());
ApplicationContainer = container;
return new AutofacServiceProvider(container);
}
Note the Insert call in there to jam your service registration at the top, before their startup filter.
The new order of operations will be:
At app startup...
Your startup filter will add your custom request services middleware to the pipeline.
The AutoRequestServicesStartupFilter will add the RequestServicesContainerMiddleware to the pipeline.
During a request...
Your custom request middleware will set up request services based on the inbound request information.
The RequestServicesContainerMiddleware will see that request services are already set up and will do nothing.
When services are resolved, the request service scope will already be the tenant scope as set up by your custom request middleware and the correct thing will show up.
I tested this locally by switching the tenant ID to come from querystring rather than host name (so I didn't have to set up hosts file entries and all that jazz) and I was able to switch tenant by switching querystring parameters.
Now, you may be able to simplify this a bit. For example, you may be able to get away without a startup filter by doing something directly to the web host builder in the Program class. You may be able to register your startup filter right with the ContainerBuilder before calling builder.Populate and skip that Insert call. You may be able to store the IServiceProvider in the Startup class property if you don't like having Autofac spread through the system. You may be able to get away without a static container property if you create the middleware instance and pass the container in as a constructor parameter yourself. Unfortunately, I already spent a loooot of time trying to figure out the workaround so I'm going to have to leave "optimize it" as an exercise for the reader.
Again, sorry this wasn't clear. I've filed an issue on your behalf to get the docs updated and maybe figure out a better way to do this that's a little more straightforward.
I have an alternate solution, related to work I've done on a pending PR on the Autofac DI extension. The solution there can't be used exactly, because it depends on classes that are (rightly) internal. It can be adapted by providing shims that reproduce the functionality in those classes. Since they are compact, this doesn't require the addition of a lot of code. Until the functionality is fixed, this is the solution I'm using.
The other aspect of the solution is to eschew the custom middleware and instead make the ITenantIdentificationStrategy a service that can take any dependency required to do what it needs to.
Fixing the DI
The "DI" side of the problem is that the Autofac DI extension uses resolution to supply IServiceProvider and IServiceScopeFactory implementations. This is possible, because under the hood these are IComponentContext and ILifetimeScope (which are themselves different interfaces for the same thing). In most cases this works fine, but ASP.NET Core proceeds by resolving a singleton IServiceScopeFactory very early in the application cycle. In a multi-tenant scenario this resolution will return the ILifetimeScope for either the first tenant requested, or for the "default" tenant, and that will be the root scope (as far as MS DI is concerned) for the application lifetime. (See the PR for further discussion.)
The classes below implement an alternate behavior: instead of resolving the DI interfaces, it builds (news-up) the initially-requested ones from the IContainer directly. With the initial IServiceScopeFactory based directly on IContainer, further scope requests will resolve correctly.
public class ContainerServiceProvider : IServiceProvider, ISupportRequiredService
{
private readonly IContainer container;
public ContainerServiceProvider(IContainer container)
{
this.container = container;
}
public object GetRequiredService(Type serviceType)
{
if (TryGetContainer(serviceType, out object containerSvc)) return containerSvc;
else return container.Resolve(serviceType);
}
public object GetService(Type serviceType)
{
if (TryGetContainer(serviceType, out object containerSvc)) return containerSvc;
else return container.ResolveOptional(serviceType);
}
bool TryGetContainer(Type serviceType, out object containerSvc)
{
if (serviceType == typeof(IServiceProvider)) { containerSvc = this; return true; }
if (serviceType == typeof(IServiceScopeFactory)) { containerSvc = new ContainerServiceScopeFactory(container); return true; }
else { containerSvc = null; return false; }
}
}
// uses IContainer, but could use copy of AutofacServiceScopeFactory
internal class ContainerServiceScopeFactory : IServiceScopeFactory
{
private IContainer container;
public ContainerServiceScopeFactory(IContainer container)
{
this.container = container;
}
public IServiceScope CreateScope()
{
return new BecauseAutofacsIsInternalServiceScope(container.BeginLifetimeScope());
}
}
// direct copy of AutofacServiceScope
internal class BecauseAutofacsIsInternalServiceScope : IServiceScope
{
private readonly ILifetimeScope _lifetimeScope;
/// <summary>
/// Initializes a new instance of the <see cref="AutofacServiceScope"/> class.
/// </summary>
/// <param name="lifetimeScope">
/// The lifetime scope from which services should be resolved for this service scope.
/// </param>
public BecauseAutofacsIsInternalServiceScope(ILifetimeScope lifetimeScope)
{
this._lifetimeScope = lifetimeScope;
this.ServiceProvider = this._lifetimeScope.Resolve<IServiceProvider>();
}
/// <summary>
/// Gets an <see cref="IServiceProvider" /> corresponding to this service scope.
/// </summary>
/// <value>
/// An <see cref="IServiceProvider" /> that can be used to resolve dependencies from the scope.
/// </value>
public IServiceProvider ServiceProvider { get; }
/// <summary>
/// Disposes of the lifetime scope and resolved disposable services.
/// </summary>
public void Dispose()
{
this._lifetimeScope.Dispose();
}
}
Fixing Identification Strategy
As for making the identification-strategy a service, I would rework your implementation like so:
public class MultitenantIdentificationStrategy : ITenantIdentificationStrategy
{
public const string DefaultTenantId = null;
private readonly IHttpContextAccessor contextaccessor;
public MultitenantTenantIdentificationStrategy(IHttpContextAccessor contextaccessor)
{
this.contextaccessor = contextaccessor;
}
public bool TryIdentifyTenant(out object tenantId)
{
var context = contextaccessor.HttpContext;
// after this is unchanged
.
.
}
.
.
}
Use in Startup.ConfigureServices
This shows the fragment of how these last few pieces are registered and fed to MS DI for ASP.NET.
. . .
builder.RegisterType<MultitenantIdentificationStrategy>().AsImplementedInterfaces(); // tenant identification
// register do Autofac DI integration
builder.Populate(services);
var underlyingcontainer = builder.Build();
ApplicationContainer = new MultitenantContainer(underlyingcontainer.Resolve<ITenantIdentificationStrategy>(), underlyingContainer);
return new ContainerServiceProvider(ApplicationContainer);
If you find this solution workable, please give a thumbs up to DI PR 10--or PR 11, if after reviewing you think that is the better/more elegant solution. Either will save having to add the "shim" code above.

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];

Repositories and Services, MVC Model

So I've been learning about the Repository model, and it seems that it is expected that Repositories do not do a lot of intricate logic. However I also read that most of the business logic should not be inside of my Controllers. So where do I put it?
I've looked at some sample applications and it seems that they have another layer called Services that do more intricate logic for things. So how does this factor into the MVC pattern?
Do I want to build my services to access my repositories, and then my controllers to access my services? Like this?
interface IMembershipService
{
bool ValidateUser(string username, string password);
MembershipCreateStatus Create(string username, string password);
}
interface IMembershipRepository
{
MembershipCreateStatus Create(string username, string password);
}
class MembershipRepository : IMembershipRepository
{
public MembershipRepository(ISession session)
{
**// this is where I am confused...**
}
}
class MembershipService : IMembershipService
{
private readonly IMembershipRepository membershipRepository;
public MembershipService(IMembershipRepository membershipRepository)
{
this.membershipRepository = membershipRepository;
}
public bool ValidateUser(string username, string password)
{
// validation logic
}
public MembershipCreateStatus Create(string username, string password)
{
return membershipRepository.Create(username, password);
}
}
class MembershipController : Controller
{
private readonly IMembershipService membershipService;
public MembershipController(IMembershipService membershipService)
{
this.membershipService = membershipService
}
}
The marked part of my code is what confuses me. Everything I have read said I should be injecting my ISession into my repositories. This means I could not be injecting ISession into my services, so then how do I do Database access from my Services? I'm not understanding what the appropriate process is here.
When I put ValidateUser in my IMembershipRepository, I was told that was 'bad'. But the IMembershipRepository is where the database access resides. That's the intention, right? To keep the database access very minimal? But if I can't put other logic in them, then what is the point?
Can someone shed some light on this, and show me an example that might be more viable?
I am using Fluent nHibernate, ASP.NET MVC 3.0, and Castle.Windsor.
Should I instead do something like ...
class MembershipService
{
private readonly IMembershipRepository membershipRepository;
public MembershipService(ISession session)
{
membershipRepository = new MembershipRepository(session);
}
}
And never give my Controllers direct access to the Repositories?
Everything I have read said I should be injecting my ISession into my repositories.
That's correct. You need to inject the session into the repository constructor because this is where the data access is made.
This means I could not be injecting ISession into my services, so then how do I do Database access from my Services?
You don't do database access in your services. The service relies on one or more repositories injected into its constructor and uses their respective methods. The service never directly queries the database.
So to recap:
The repository contains the simple CRUD operations on your model. This is where the data access is performed. This data access doesn't necessary mean database. It will depend on the underlying storage you are using. For example you could be calling some remote services on the cloud to perform the data access.
The service relies on one or more repositories to implement a business operation. This business operation might depend on one or more CRUD operations on the repositories. A service shouldn't even know about the existence of a database.
The controller uses the service to invoke the business operation.
In order to decrease the coupling between the different layers, interfaces are used to abstract the operations.
interface IMembershipService
{
bool ValidateUser(string username, string password);
MembershipCreateStatus Create(string username, string password);
}
Creating a service like this an anti-pattern.
How many responsibilities does a service like this have? How many reasons could it have to change?
Also, if you put your logic into services, you are going to end up with an anemic domain. What you will end up with is procedural code in a Transaction Script style. And I am not saying this is necessarily bad.
Perhaps a rich domain model is not appropriate for you, but it should be a conscious decision between the two, and this multiple responsibility service is not appropriate in either case.
This should be a HUGE red flag:
public MembershipCreateStatus Create(string username, string password)
{
return membershipRepository.Create(username, password);
}
What is the point? Layers for the sake of layers? The Service adds no value here, serves no purpose.
There are a lot of concepts missing.
First, consider using a Factory for creating objects:
public interface IMembershipFactory {
MembershipCreateStatus Create(string username, string password);
}
The factory can encapsulate any logic that goes into building an instance or beginning the lifetime of an entity object.
Second, Repositories are an abstraction of a collection of objects. Once you've used a factory to create an object, add it to the collection of objects.
var result = _membershipFactory.Create("user", "pw");
if (result.Failed); // do stuff
_membershipRepository.Add(status.NewMembership); // assumes your status includes the newly created object
Lastly, MyEntityService class that contains a method for every operation that can be performed on an Entity just seems terribly offensive to my senses.
Instead, I try to be more explicit and better capture intent by modeling each operation not as a method on a single Service class, but as individual Command classes.
public class ChangePasswordCommand {
public Guid MembershipId { get; set; }
public string CurrentPassword { get; set; }
public string NewPassword { get; set; }
}
Then, something has to actually do something when this command is sent, so we use handlers:
public interface IHandle<TMessageType> {
void Execute(TMessageType message);
}
public class ChangePasswordCommandHandler : IHandle<ChangePasswordCommand> {
public ChangePasswordCommandHandler(
IMembershipRepository repo
)
{}
public void Execute(ChangePasswordCommand command) {
var membership = repo.Get(command.MembershipId);
membership.ChangePassword(command.NewPassword);
}
}
Commands are dispatched using a simple class that interfaces with our IoC container.
This helps avoids monolithic service classes and makes a project's structure and location of logic much clearer.