ASP.Net StructureMap Injecting Previously Objects as Dependencies - asp.net

(TLDR? Skip to the last couple of paragraphs for the questions...)
I have a classic ASP.Net site which was originally built around a data access layer consisting of static methods wrapping around ADO.Net. More recently, we've been introducing abstraction layers separated by interfaces which are glued together by StructureMap. However, even in this new, layered approach the repository layer still wraps around the old static ADO.Net classes (we weren't prepared to take on the task of implementing an ORM whilst simultaneously reorganising our application architecture).
This was working fine - until today. Whilst investigating some unexpected performance issues we've been having lately we noticed a couple of things about our data access classes:
Our SqlDataConnection instances aren't always being closed.
The connection objects are being stored in static variables.
Both of the above are bad practice and likely to be significantly contributing to our performance problems. The reason why the connections were being set in static variables was to share them across data access methods which is a good idea in theory - it's just a terrible implementation.
Our solution is to convert the static data access classes/methods into objects - with our core DataManager class being instantiated once at the beginning of a request and disposed once at the end (via a new PageBase class in the web layer - much of our code is not yet separated into layers). This means we have one instance of the data access class which gets used for the entire life cycle of the request and therefore only one connection.
The problem starts now when we get to the areas of the site using the newer layered architecture. With the older code, we could just pass a reference to the DataManager instance directly to the data access layer from the code behinds but this doesn't work when the layers are separated by interfaces and only StructureMap has knowledge of the different parts.
So, with all of the background out of the way here's the questions:
Is it possible for StructureMap to create instances by passing previously instantiated objects as dependencies - within the context of a single ASP.Net Page lifecycle?
If it is possible, how is this achieved? I haven't seen anything obvious in my searching and haven't had to do this in the past.
If it is not possible, what might be an alternative solution to the problem I've described above?
NOTE: This may or may not be relevant: we're calling ObjectFactory.BuildUp( this ) in a special base page for those pages which have been converted to use the new Architecture - ASP.Net doesn't provide a good access point.

Okay, this wasn't so hard in the end. Here's the code:
var instantiatedObject = new PropertyType();
ObjectFactory.Configure( x =>
{
x.For<IPropertyType>().Use( () => instantiatedObject );
x.SetAllProperties( p => p.OfType<IPropertyType>() );
}
);
We just put this in our PageBase class before the ObjectFactory.BuildUp( this ) line. It feels slightly dirty to be putting IoC configuration in the main code like this - but it's classic ASP.Net and there aren't many alternatives. I guess we could have provided some abstraction.

Related

Ninject - define mapping in web.config file

I'm using Ninject as the IoC container for my ASP.NET MVC app. What I'm currently doing is I have The following layers in my project:
Core
Factory
Infrastructure
Logic
UI (ASP.NET MVC)
Infrastructure, Logic and UI all have references to Core and Factory has references to all.
When my ASP.NET application loads, I call a method in my Factory and pass it an enum value that tells it who runs it (UI or any other UI equivalent layer - for instance, I would like UI to work against Cache classes and Backoffice project to skip the Cache implementation of an interface and work directly against the database). The method then checks the enum and does the mapping in Ninject accordingly.
First off, is what I'm doing here is good practice? each layer doesn't know the layer next to it, and therefor loosely coupled. But on the other hand, the factory has references to all layers - which makes it tightly coupled.
Second, my mappings are hard coded in my Factory layer - what I would like to have is the mappings in a .config file (web.config) - is this possible?
Thanks
Inevitably, your solution will always have at least one project that everything else depends on. Otherwise, you could just break things out into separate solutions, because you'd have entirely separate applications. The goal is to remove duplication and create areas of responsibility; dependencies are a given.
As far as Ninject configuration goes, there is support for XML configuration. Unfortunately the docs are poorly designed and don't allow deep-linking, so I can't just simply give you a URL to go to. However, if you head over to http://www.ninject.org/wiki.html, and on the left, expand the "Ninject" heading, then "Using Ninject", and finally "Xml Configuration", you'll get the info you need.
Usually one should work with composition roots. The composition root (usually the UI) defines which bindings (mappings) are used and instanciates the object-graph in one go (well.. not always feasible but the goal is to be as close to this ideal as possible).
If i understand you correctly, you have replaced having multiple composition roots by having a factory with "enum" parameters. Probably so there's on single instance/layer responsible for mappings. The (preferred?!) alternative is to move this to the composition root, where you won't need an "switch(enum)". To reduce code duplication, put the shared bindings into a separate assembly or config file which you reuse. You might also want to look into NinjectModule's which can help you with that.
As far as ninject configuration by XML goes, i would recommend against that. It's far more brittle (renamings and the like). Only do it if you have mappings which you need to be able to modify after implementation. However, for most configuration issues it's entirely possible (and recommended) to do it differently. For example:
config file:
DatabaseProvider = MicrosoftSQL // OracleSQL if you want to use Oracle DB...
ninject binding:
Bind<IDatabaseProvider>().To<MicrosoftSqlDatabaseProvider>()
.When(x => config.DatabaseProvier == "MicrosoftSQL");
Bind<IDatabaseProvider>().To<OracleSqlDtabaseProvider>()
.When(x => config.DatabaseProvier == "OracleSQL");

Entity Framework ( Questions on POCO, Context, and DTO)

I have been reading about entity framework over the past couple of days and have managed to get a fair idea of using it but I still have a couple of questions some of which might seem a bit too basic. For perspective I am using entity framework 4.0 in an asp.net web application.If you can answer any of the questions please go ahead.
What advantage do I get by using POCO templates. I understand that if I wish to get persistence ignorance and keep my Entities clear of any information related to storage POCO entities are the way to go. Also I could switch from Entity framework to say NHibernate with relative ease when using POCO entities? Apart from loose coupling is there any significant reason for me to go towards POCO entities. Also if I do use POCO do I end up losing anything. I still get change tracking and lazy loading with the help of proxies?
Is it normal practice to use the Entities of the EF model as Data transfer Objects or Business Objects. i.e for example I have a separate class library for my entity model.Supposing I am using MVP , where I want a list of Employee's in a company. The presenter would request my business logic functions which would query the entity model for the list of Employee's and return the list of entities to the presenter. In this case my presenter would need to have a reference to the EF model. Is this the correct way? In the case of my asp.net web applciation it shouldnt be a problem but if I am using web services how does this work? Is this the reason to go towards POCO entities?
Supposing The Employee entity has a navigation property to a company table. If I use and wrap the data context in an 'using' block , and try to access the navigation property in the BL I am assuming I would get an exception. Would I also get an exception if I turned off lazyloading and used the 'include' linq query to get the entity? On a previous post someone recommended I use an context per request implying that the context remains active even when I am in the BL. I am assuming I would still need to detach the object and attach it to the context on my next request if I wish to persist any changes I make? or Instead should I just query for the object again with the new context and update it?
This question has more to do with organizing files/best practices and is a followup to a question i posted earlier. When I am using separate files based on entities to organize my data access layer, what is the best practice to organize my queries involving joins between multiple tables. I am still a bit hazy on organization. Have tried searching online but havent had much help.
Terrific question. My first recommendation is to think in patterns. With that said...
You pretty much nailed the advantages of using POCO. There are some distinct advantages to decoupling your business objects (POCO entities) from your data access layer. But the primary reason is like you said the ability to change or modify layers below. However using POCO you are essentially following the Code First (CF) approach. Personally, I consider it Code In Parallel depending upon your software development life cycle. You still have all the bells and whistles that data or model first approach have and some since you can extend the DbContext which is ObjectContext under the hood. I read an article, which I cannot seem to find, that CF is the future of Entity Framework. Lastly the nice thing with POCO is you are able to incorporate validation rules here or else where. You can also provide projections. Lets say you have Date of Birth but you want an Age property as well. That now becomes a no brainer as the Age property is ignored when mapping to the database.
Personally I create my own business objects (POCO) for large projects that tend to have a life of its own where change is a way of life. Another thought is scalability and maintainability. What if down the road I choose to split functionality between applications where, like you mentioned web services, functionality is now delivered from two disparate locations. If you have encapsulated your business objects and DAL within the same code block separation or scalability has now become a bit more complex. However, consider the project. It may be small with very little future change so no need to throw a grenade to kill a fly. At which time data first might be the way to go and let edmx file represent your objects. So don't marry yourself to one technology or one methodology/pattern. Do what makes sense for your time and business.
Using statements are perfectly fine. In fact I've recently been turned on to then wrapping that within a TransactionScope. If an error occurs rollbacks are inherent. Next, something to consider is the UnitOfWork. UnitOfWork pattern encapsulates a snapshot of what needs to be performed where the Data Context is the boundaries from which you work within. For each UnitOfWork you have a subject for which work is to be performed on. For example an Employee. So if you are to save Employee information to keep it simple you would make a call to the BL service or repository (which ever). There you pass in the Employee Id, perform some work under that UnitOfWork where it is either instantiated in the constructor or using Dependency Injections (DI or IoC). Easy starter is StructureMap. There the service makes the necessary calls to your UnitOfWork (DbContext) then returns control back upstream (e.g. UI).
The best way to learn here is to view others code. I'd start with some Microsoft examples. I'd start with Nerd Dinner (http://nerddinner.codeplex.com/) then build off that.
Additional Reading:
Use prototype pattern or not
http://weblogs.asp.net/manavi/archive/2011/05/17/associations-in-ef-4-1-code-first-part-6-many-valued-associations.aspx
[EDIT]
NightHawk457, I'm terribly sorry for not responding to your questions. Hopefully you figured it out but for future readers...
To help everyone visualize, imagine the below Architecture using the Domain Model and Repository as an example. Remember, there are many ways to skin a cat so take this and make it your own and don't forget my Grenade comment above.
Data Layer (Data Access): MyDbContext : DbContext, IUnitOfWork, where IUnitWork contracts the CRUD operations.
Data Repository (Data Access / Business Logic): MyDomainObjectRepository : IMyDomainObjectRepository, which receives IUnitOfWork by Factory class or Dependency Injection. Calls MyDomainObject validation on CRUD operations.
Domain Model (Business Logic): MyDomainObject using [Custom] Validation Attributes. Read this for pros/cons.
MVVM / MVC / WCF (Presentation / Service Layers): What ever additional layers you chose, you now have access to your data which is wrapped nicely in smaller modules who are self encapsulating of their function. The presentation layer (e.g. ViewModel, Controller, Code-Behind, etc.) can then receive an IMyObjectRepository by a Factory class or by Dependency Injection.
Tips:
Pass connection string into MyDbContext so you can reuse MyDbContext.
MySql does not play well with System.Transactions.TransactionScope, example. I don't recall exactly but it was something MySql did not support. This makes Testing a bit difficult since we have created this level of separation.
Create a Test project for each layer and at the minimum test general functionality/rules.
Each Domain Object should extend base object with ID field at minimum. Also do not implement Key attributes here. Domain Object should not describe architecture but rather the specific data as an entity. Even on Code First this can be achieved by the Fluent API.
Think generics when creating MyDbContext. ;) Read Diego's post.
In ASP.NET, the repositories are nice to use with ObjectDataSources.
As you can see, there is clear separation of roles where IUnitOfWork and IMyDomainObjectRepository are the Interfaces which expose the above layers functionality. And as an example, IUnitOfWork could be NHibernate, Entity Framework, LinqToSql or ADO.NET where a change to the factory class or dependency injection registration is all that has to change. FYI, I've heard the Repository called the Service Layer as well. Personally I like the first name to not be confused with Web Services. The next big take away from this structure is realizing the scope for you Database Context (IUnitOfWork). A simple example would be a ASP.NET page where for each page there is one and only one IUnitOfWork for either each repository or for that scope of work. Same holds true for ViewModels, Controllers, etc. So let's say you need to utilize two repositories, EmployeeRepository and HRRepository. You then could share the IUnitOfWork between both or not. To cross page, ViewModel or Controller boundaries, we use the ID for entities where they are then pulled from the DB and work is performed. You could alternatively pass a DTO across boundaries and attach to the context but then you begin losing separation of layers.
To continue, POCO classes do not have to be auto generated. In fact you can create your Entity Classes from scratch and perform the mapping in your extended DbContext class inside the OnModelCreating(DbModelBuilder mb) method. Start here, then here and note the Additional Resources, google Fluent API and read this post by Diego.
As for validation, this is an interesting point because it would be GREAT if all Business Rules could be validated in one location. Well, as we all know that doesn't work real well. So here is my recommendation, keep all data level validation (i.e. required, range, format, etc.) with data annotation as much as possible in the domain object and leave process validation in the Repository with clear roles of the Repository (i.e. if (isEmployee) do this, else that). I say clear, such that you do not want to add an Employee in two different Repositories where validation has to be duplicated. To call the validation, start here. Capture the ValidationResults and send upstream with a MyRepositoryValidationException which contains a collection of validations errors (e.g. Employee is required) which can be presented to the presentation layer. With all that said, don't forget to perform validation at the presentation layer. You don't want post backs to make sure an Employee has a valid Email, for example.
Just remember to balance time and effort with complexity. For something simple, use Data First or Model First with your EDMX file. Then lay a repository on top of that which also contains all the validation rules.

Using multiple ObjectContexts in Entity Framework 4 with the repository/uow pattern

i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed in this post. In the code, there is a line that delegates the setup of an ObjectContext in global.asax.
EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());
On the web page code-behind, you can create a generic repository interface like so ...
IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();
My question is what is a good approach to refactoring this code so that I can use more than one ObjectContext and differentiate between them in the code-behind? Basically i have two databases/entity models in my application and need to query them both on the same page.
The Unit of Work is used to manage persistence across multiple repositories, not multiple object contexts.
You're not going to be able to persist changes across multiple contexts using a unit of work, as the UoW is simply implemented as a wrapper for a ObjectContext. Therefore, you'll need two unit of works.
Overall, things are going to get messy. You're going to have two OCs newed up and disposed each HTTP request, not to mention transaction management is going to be a nightmare.
Must you have two ObjectContexts? What is the reasoning for this? If it's for scalability, don't bother; it's going to be too painful for other things like your repository, unit of work and http scope management.
It's hard to provide good advice without seeing how you have your repositories set up.
Try creating wrapper classes for each object context, each implementing IUnitOfWork and a secondary unique interface (IEfSqlContext1, etc which represents one of your models/contexts).
Then you can inject whichever context you want.
As I said though, try and avoid having two EDMX/Contexts. It's more trouble than it's worth.

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.

Where do you put program scope variables in UI driven application?

Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program.
I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?
I'm just wondering what others do to organize their programs without breaking the rules?
I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.
The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.
The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.
A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .
Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.
Place your singleton in the theApp
class CsolverApp : public CWinApp
{
public:
cData theData;
…
Now to access this from anywhere in your code
#include “solver.h”
theApp.theData.somepublicmethod();
It does make sense to look at this from the MVC (Model - View - Controller) viewpoint. (That the naming of MFC is an homage to MVC is another sick joke on Microsoft's part; it is hard and unintuitive (but by no means impossible) to manage the types of abstractions that are necessary in "true" MVC within MFC.)
Specifically, it sounds like you've thought out the basis for MVC design; you have the classes that do the underlying business logic work (the Model), and you know they should be separated from the UI components (the View). The issue that comes in now is the third part of the MVC trinity; the Controller.
MFC makes this stuff tough by apparently purposefully obfuscating the MVC process, by making you start with a Dialog. In your instance, the Dialog that MFC is starting you off with should be the Controller, and NOT the View. What your Dialog (Controller) is doing for you is managing your UI components (View) and allowing them to interact with your "work" classes (Model). What makes this tough again is that your UI components, to be visible, most likely need to be attached to your Dialog to be visible.
To get this sort of thing right, you really have to basically implement your Controller as a high-level object that gets instantiated from your Dialog; your Dialog is where the initial control flow comes in, your Controller gets control flow, and from there, it should treat the Dialog as just another UI component (albeit one with special status).
This allows you to have the proper level of encapsulation; your Controller invokes your business logic (Model) classes, which can communicate with each other or with the Controller as appropriate; they are segregated from the View by the Controller, instead of being embedded in the UI components and (likely) taking the "easy way" of over-privileged access to UI elements ("Hmm, I need this object to get some input from the user; I could refactor, but it'll be so much easier to just throw a dialog box up, since I have the top-level window handle...").
Once your Controller object is the home to all of the business logic objects, things become easier; you can use the Controller to provide cross-object access for any objects that need other objects. Think about which classes need to be Singletons, and use them sparingly. Resources that need contention management (such as hardware resources) are great examples of "natural singletons"; things which lend themselves to a singleton approach. You may also choose to make your Controller a singleton; depending on the requirements for access to it. Specifically, in your Dependency Injection scenario, the Controller is where you'd instantiate the objects and manage the dependencies.
This is the basic MVC approach; but, like I say, MFC makes it unusually hard and unintuitive, because of the fundamental design of MFC. I learned MUCH more about MVC AFTER an initial VERY negative impression about it due to MFC; if you can, I recommend looking into what MVC implementations look like in other languages.
Good luck!
If I am understanding you correctly, it sounds like the lifetime of your dialog objects is too long. Rather than maintaining the dialogs for the duration of your program, you should consider creating and destroying them as they are needed.
Also, global variables (or singletons) are OK so long as the thing that the variable represents is truly a global thing that persists for the lifetime of the program, rather than just a place-holder for an object of lesser duration. Using globals for the wrong things for simplicity sake will come back to bite you eventually, even if the globals are stored on the main dialog.

Resources