How would you approach isolating a dependency resolver to one area in MVC3? - asp.net

In the recent spirit of isolating stuff and plugging it in via NuGet, does anyone have an idea about how you'd limit a dependency resolver to just one area in MVC3? It's easy enough to keep views and controllers limited to an area, but unless I'm not seeing an obvious hook, it looks like setting an IDependencyResolver is something that unavoidably has global scope. I'd like to limit it to just one area.
Any suggestions?

IDependencyResolver is global by design. If you want to vary behavior by area, you should look at the various *Activator types and interfaces that can make decisions based on context objects.
What specifically are you trying to do?

I would suggest using the Common Service Locator for this. Basically each area could setup up the CSL for their specific container.
You will probably need to create an adapter between the dependency resolver or forgo it altogether and strictly use the CSL.
In general I am not a proponent of using the CSL in a line of business app. It's intent is to make it easier for open source components that use DI (like MassTransit) easier to integrate into line of business apps. This might be an exception however.
Also, look into the mvccontrib portable areas. It's designed for this type of thing.

What you're trying to do sounds like a bad idea. The point of dependency injection is so you can isolate specific dependencies and not have your code care where they come from.
If you're trying to restrict some objects or classes to a certain MVC area, configure your dependency injector to call the proper ones at the right time.
Some more details about what you're trying to do will help generate better answers.

Related

Generating files to multiple paths with Swagger Codegen?

I'm creating a template for our server-side codegen implementation, but I ran into an issue for a feature request...
The developers who are going to use the generated base want the following pattern (the generator is based on the dotnetcore):
Controllers
v{apiVersion}
{endpoint}ApiController : Controller, I{endpoint}Api
Interfaces
v{apiVersion}
I{endpoint}Api
I{endpoint}DataProvider
DataProviders
-v{apiVersion}
-{endpoint}DataProvider : I{endpoint}DataProvider
Both interfaces are the same, describing the endpoints. The DataProvider implementation will allow us to use DI to hot-swap the actual data provider/business logic layer during runtime.
The generated ApiControllers will refer to the IDataProviders, and use the actual implementation (the currently active one, that is). For that we're going to use dotnetcore's built-in dependency injection system.
However I can't seem to find a way to have the operations generator output to three different folders, based on the template. It will all end up jumbled in a single folder, and I will need to manually move them.
Is there a way to solve these requirements, or should I solve it all the time manually?

How to avoid setters using Symfony with admin panel creator?

I want to avoid getters/setters hell in my entities (here is the reason: http://ocramius.github.io/doctrine-best-practices/#/53), but both most popular admin panel generators:
Sonata and DoctrineORMAdminBundle
https://github.com/javiereguiluz/EasyAdminBundle
need getters and setters to render view.
My idea is to create DTO object instead (http://ocramius.github.io/doctrine-best-practices/#/57) and then use named constructors to create entities. I want to call named constructor inside my service. What is the best way to force admin panel generators to use my DTOs to persist/update data, can you give me an idea and/or example of good practices in that case?
The only way I imagined is to use DTO instead of real Entity, call prePersist/preUpdate hooks and use custom service, but it looks confusing.
One of the most important aspect of DDD is to correctly identify your bounded contexts (usually aligned with your sub-domains) and determine the appropriate technologies and architectures to use within those.
An admin panel sounds like something generic that would be very CRUD in nature. If that's the case then don't try to fight it and embrace CRUD within that BC. Trying to implement a pure domain model in a BC where it isn't needed would make things more complicated than they need to be.
However, if you determined that the complexity justifies a domain model then I would advise against using a code generator. Properly modeling the reality of a complex domain is not an easy task, and certainly not one that could be achieved by a tool.

ASP.NET plugin architecture: reference to other modules

We're currently migrating our ASP Intranet to .NET and we started to develop this Intranet in one ASP.NET website. This, however, raised some problems regarding Visual Studio (performance, compile-time, ...).
Because our Intranet basically exists of modules, we want to seperate our project in subprojects in Visual Studio (each module is a subproject).
This raises also some problems because the modules have references to each other.
Module X uses Module Y and vice versa... (circular dependencies).
What's the best way to develop such an Intranet?
I'll will give an example because it's difficult to explain.
We have a module to maintain our employees. Each employee has different documents (a contract, documents created by the employee, ...).
All documents inside our Intranet our maintained by a document module.
The employee-module needs to reference the document-module.
What if in the future I need to reference the employee-module in the document-module?
What's the best way to solve this?
It sounds to me like you have two problems.
First you need to break the business orientated functionality of the system down into cohesive parts; in terms of Object Orientated design there's a few principles which you should be using to guide your thinking:
Common Reuse Principle
Common Closure Principle
The idea is that things which are closely related, to the extent that 'if one needs to be changed, they all are likely to need to be changed'.
Single Responsibility Principle
Don't try to have a component do to much.
I think you also need to look at you dependency structure more closely - as soon as you start getting circular references it's probably a sign that you haven't broken the various "things" apart correctly. Maybe you need to understand the problem domain more? It's a common problem - well, not so much a problem as simply a part of designing complex systems.
Once you get this sorted out it will make the second part much easier: system architecture and design.
Luckily there's already a lot of existing material on plugins, try searching by tag, e.g:
https://stackoverflow.com/questions/tagged/plugins+.net
https://stackoverflow.com/questions/tagged/plugins+architecture
Edit:
Assets is defined in a different module than employees. But the Assets-class defines a property 'AssignedTo' which is of the type 'Employee'. I've been breaking my head how to disconnect these two
There two parts to this, and you might want to look at using both:
Using a Common Layer containing simple data structures that all parts of the system can share.
Using Interfaces.
Common Layer / POCO's
POCO stands for "Plain Old CLR Objects", the idea is that POCO's are a simple data structures that you can use for exchanging information between layers - or in your case between modules that need to remain loosely Coupled. POCO's don't contain any business logic. Treat them like you'd treat the String or DateTime types.
So rather than referencing each other, the Asset and Employee classes reference the POCO's.
The idea is to define these in a common assembly that the rest of your application / modules can reference. The assembly which defines these needs to be devoid of unwanted dependencies - which should be easy enough.
Interfaces
This is pretty much the same, but instead of referring to a concrete object (like a POCO) you refer to an interface. These interfaces would be defined in a similar fashion to the POCO's described above (common assembly, no dependencies).
You'd then use a Factory to go and load up the concrete object at runtime. This is basically Dependency Inversion.
So rather than referencing each other, the Asset and Employee classes reference the interfaces, and concrete implementations are instantiated at runtime.
This article might be of assistance for both of the options above: An Introduction to Dependency Inversion
Edit:
I've got the following method GetAsset( int assetID ); In this method, the property asset.AssignedTo (type IAssignable) is filled in. How can I assign this properly?
This depends on where the logic sits, and how you want to architect things.
If you have a Business Logic (BL) Layer - which is mainly a comprehensive Domain Model (DM) (of which both Asset and Employee were members), then it's likely Assets and Members would know about each other, and when you did a call to populate the Asset you'd probably get the appropriate Employee data as well. In this case the BL / DM is asking for the data - not isolated Asset and Member classes.
In this case your "modules" would be another layer that was built on top of the BL / DM described above.
I variation on this is that inside GetAsset() you only get asset data, and atsome point after that you get the employee data separately. No matter how loosely you couple things there is going to have to be some point at which you define the connection between Asset and Employee, even if it's just in data.
This suggests some sort of Register Pattern, a place where "connections" are defined, and anytime you deal with a type which is 'IAssignable' you know you need to check the register for any possible assignments.
I would look into creating interfaces for your plug-ins that way you will be able to add new modules, and as long as they follow the interface specifications your projects will be able to call them without explicitly knowing anything about them.
We use this to create plug-ins for our application. Each plugin in encapsulated in user control that implements a specific interface, then we add new modules whenever we want, and because they are user controls we can store the path to the control in the database, and use load control to load them, and we use the interface to manipulate them, the page that loads them doesn't need to know anything about what they do.

Proper way to build a data Repository in ASP.NET MVC

I'm working on using the Repository methodology in my App and I have a very fundamental question.
When I build my Model, I have a Data.dbml file and then I'm putting my Repositories in the same folder with it.... IE:
Data.dbml
IUserRepository.cs
UserRepository.cs
My question is simple. Is it better to build the folder structure like that above, or is it ok to simply put my Interface in with the UserRepository.cs?
Data.dbml
UserRepository.cs which contains both the interface and the class
Just looking for "best practices" here. Thanks in advance.
General best practice is to have one class or one interface per file.
Here's the more generic discussion, which I think applies to your case:
One class per file rule in .NET?
As a developer new to your project, I would appreciate knowing that IUserRepository exists--without having to fish through your UserRepository.cs file.
Do whatever makes sense to you.
Personally I find browsing solutions for anything painful so I have hot keyed Goto Definition/Implementation and Resharpers FindUsages Go to Type, Go to File so I never have to click anything.
Combining interfaces and classes in one file makes sense if the class or interfaces are small.
Also if your following the Liskov substitution principal / a dependency injection strategy and general good design practices you would rarely be interacting with actual implementations anyway. Repositories should almost never be referred to by their concrete implementation.

What Does the DRY Principle Actually Look Like in ASP.NET MVC?

I keep hearing about the DRY Principle and how it is so important in ASP.NET MVC, but when I do research on Google I don't seem to quite understand exactly how it applies to MVC.
From what I've read its not really the copy & paste code smell, which I thought it was, but it is more than that.
Can any of you give some insight into how I might use the DRY Principle in my ASP.NET MVC application?
DRY just means "Don't Repeat Yourself". Make sure that when you write code, you only write it one time. If you find yourself writing similar functionality in all of your Controller classes, make a base controller class that has the functionality and then inherit from it, or move the functionality into another class and call it from there instead of repeating it in all the controllers.
use filter attributes to manage aspects (authentication, navigation, breadcrumbs, etc)
use a layer supertype controller (apply common controller-level filters to it, see mvccontrib for an example)
write custom actionresults (like in mvccontrib - for example we made one called logoutresult that just does a FormsAuthentication.Logout()
use a convention for view names
most importantly - keep you controller actions dumb, look for reuse opportunities in services
Don't Repeat Yourself. It can apply to many different aspects of programming. The most basic level of this is prevent code smell. I haven't used ASP.NET so I can't get specific to it and MVC's.
In C++ Templating prevets multiple copies of the same function.
In C void * pointers can be used in a similar fashion, but with great care.
Inheriting from another function allows function allows other functions to use the same code base without having to copy the code.
Normalizing data in a database minimizes redundant data. Also adhereing to the DRY principle.
When you go over a "thought" in a project. Ask yourself.
Have I already wrote this code?
Will this code be useful elsewhere.
Can I save coding by building off of a previous class/function.
DRY is not specific to any one technology. Just make sure you look at your classes from a functionality standpoint (not even from a copy/paste coder view) and see where the duplication occurs. This process will probably not happen in one sitting, and you will only notice duplication after reviewing your code several months later when adding a new feature. If you have unit tests, you should have no fear in removing that duplication.
One advantage of MVC as related to not repeating yourself is that your controller can do tasks common to all pages in the one class. For example, validating against certain types of malicious requests or validating authentication can be centralized.
DRY should not only be applied to code, but to information in general. Are you repeating things in your build system? Do you have data which should be moved to a common configuration file, etc.
Well, the most common example that I can give about DRY and UI is using things like MasterPages and UserControls.
MasterPages ensure that you have written all the static HTML only once.
UserControls ensure reusability of code. Example, you will have a lot of forms doing basic stuff like CRUD. Now, ideally we want all users to see different pages for Create and Update though the forms fields in both will almost be the same. What we can do is combine all the common controls and put them into a control that can be reused over both the pages. This ensures that we are never retyping (or copy-pasting) the same code.
DRY is especially important in MVC because of the increase in the sheer number of files to accomplish the same task.
There seems to be a misconception that everything in a domain model has to be copied up as a special view model. You can have domain models be domain models but view models be something that know nothing of domain specifics and be more generic. For example:
Domain Model classes: Account, Asset, PurchaseOrder
View Model: List, Table, Tuple, SearchFormBackingModel:Checked options, Outputoptions, etc. The view itself might be much more view implementation specific.
The Tuple/Dictonary/Map might map to Account, Asset and PurchaseOrder single instances but a Table might be useful for a collection of them etc. You still have MVC but you have session data, not ready for transaction yet in a view model without necessarily having it violate the rules of your domain model which is where the rules should go. They will be less anemic and anti-pattern that way. You can pass these rules up front and use them there or just in back or both depending on how the system reads from clients etc.

Resources