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");
Related
We are starting to develop a new asp.net mvc 5 application that should be multilingual.
I found a very nice tutorial how to get this working. The only thing I wonder about this tutorial is, that the author suggests to create a separate project inside the solution for the resources.
Now my question: Is this recommended?
I usually create a folder called Resources inside my MVC project. Although if you wish to reference your resources from other projects, you may wish to create them inside a separate project.
I then sub-folder based on my controller names and change the 'Custom Tool' property to 'PublicResXFileCodeGenerator'.
When I use the resource strings in my Views, it looks like:
<title>#Resources.Home.Index.PageTitle</title>
Personally, I prefer to use a folder rather than a project, as this forces me to not generate UI strings in my application layers and forces me to find better ways to solve problems where I might end up generating strings in my business logic that might end up in the UI.
We have resource files in projects where they are most relevant.
We have a component that handles the translation of resources on different levels
( also for Winforms and WPF...)
and we group resource files according to functional importance,
bussiness level messages in a project for the Bussiness layer,
a project for common translations used by our standard code.
A .NET ResourceManager can handle one resource file, so our manager keeps a list of ResourceManagers.
At runtime you just try them all ( or work with logical category names to speed up the lookup)...
(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.
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.
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.
I am VERY new to ASP.NET. I come from a VB6 / ASP (classic) / SQL Server 2000 background. I am reading a lot about Visual Studio 2008 (have installed it and am poking around). I have read about "reflection" and would like someone to explain, as best as you can to an older developer of the technologies I've written above, what exactly Reflection is and why I would use it... I am having trouble getting my head around that. Thanks!
Reflection is how you can explore the internals of different Types, without normally having access (ie. private, protected, etc members).
It's also used to dynamically load DLL's and get access to types and methods defined in them without statically compiling them into your project.
In a nutshell: Reflection is your toolkit for peeking under the hood of a piece of code.
As to why you would use it, it's generally only used in complex situations, or code analysis. The other common use is for loading precompiled plugins into your project.
Reflection lets you programmatically load an assembly, get a list of all the types in an assembly, get a list of all the properties and methods in these types, etc.
As an example:
myobject.GetType().GetProperty("MyProperty").SetValue(myobject, "wicked!", null)
It allows the internals of an object to be reflected to the outside world (code that is using said objects).
A practical use in statically typed languages like C# (and Java) is to allow invocation of methods/members at runtime via a string (eg the name of the method - perhaps you don't know the name of the method you will use at compile time).
In the context of dynamic languages I haven't heard the term as much (as generally you don't worry about the above), other then perhaps to iterate through a list of methods/members etc...
Reflection is .Net's means to manipulate or extract information of an assembly, class or method at run time. For example, you can create a class at runtime, including it's methods. As stated by monoxide, reflection is used to dynamically load assembly as plugins, or in advance cases, it is used to create .Net compiler targeting .Net, like IronPython.
Updated: You may refer to the topic on metaprogramming and its related topics for more details.
When you build any assembly in .NET (ASP.NET, Windows Forms, Command line, class library etc), a number of meta-data "definition tables" are also created within the assembly storing information about methods, fields and types corresponding to the types, fields and methods you wrote in your code.
The classes in System.Reflection namespace in .NET allow you to enumerate and interate over these tables, providing an "object model" for you to query and access items in these tables.
One common use of Reflection is providing extensibility (plug-ins) to your application. For example, Reflection allows you to load an assembly dynamically from a file path, query its types for a specific useful type (such as an Interface your application can call) and then actually invoke a method on this external assembly.
Custom Attributes also go hand in hand with reflection. For example the NUnit unit testing framework allows you to indicate a testing class and test methods by adding [Test] {TestFixture] attributes to your own code.
However then the NUnit test runner must use Reflection to load your assembly, search for all occurrences of methods that have the test attribute and then actually call your test.
This is simplifying it a lot, however it gives you a good practical example of where Reflection is essential.
Reflection certainly is powerful, however be ware that it allows you to completely disregard the fundamental concept of access modifiers (encapsulation) in object oriented programming.
For example you can easily use it to retrieve a list of Private methods in a class and actually call them. For this reason you need to think carefully about how and where you use it to avoid bypassing encapsulation and very tightly coupling (bad) code.
Reflection is the process of inspecting the metadata of an application. In other words,When reading attributes, you’ve already looked at some of the functionality that reflection
offers. Reflection enables an application to collect information about itself and act on this in-
formation. Reflection is slower than normally executing static code. It can, however, give you
a flexibility that static code can’t provide