Tell C# to use Castle to create objects - asp.net-mvc-2

I think my question is a long shot.
Lets say I have an attribute:
public sealed class MyCustomAttribute: ActionFilterAttribute
Used on a class method
[MyCustomAttribute]
public virtual ActionResult Options(FormCollection collection)
Now, I need to add a contructor's parameter
public MyCustomAttribute(IMyDependentObject dependentObject)
{
(...)
}
(You propably notice that it's some Asp.NET MCV code)
I would like to use DI to create this attribute. Asp.NET MVC code automatically create it and I don't know how/where I could write code to use Castle istead.
Any ideas?

As far a I konw castle does not support injection of existing objects, which makes it impossible to inject attributes as their construction is not under your control. Other IoC containers such as Ninject support injection of existing objects. They inject properties of your attribut filter. See http://github.com/ninject/ninject.web.mvc for an extension that exactly does what you need.
What you can do if you want to stay on castle is to inject your own ControllerActionInvoker derived from ControllerActionInvoker (AsyncControllerActionInvoker in case of async controller) into all controllers. In your own invoker you override GetFilters. Additionally to the Filters returned by the base you add FilterInfos that are created by castle.
The decision which filters infos are created and added can be achieved with various strategies e.g.:
Add an own custom attribute that contains the information e.g. name of a binding
A configuration file/database
May you consider switching to MVC3 this makes all a bit easier. As you can register your own FilterProvider which makes all much easier. In this FilterProvider you have to decide which filter info you want to add. See again the two strategies above. See http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html for information about MVC3 and filters.

Related

Am I properly creating my interface for a partial DbContext class in EF6?

I am utilizing ASP.NET WebAPI 2 & EF6 for a very small project which utilizes AutoFac to inject my DbContext directly into my controllers. I am not using a repository pattern as per Ryan's answer here: NOT using repository pattern, use the ORM as is (EF). To perform the injection, I went ahead and created an interface like so:
public interface IMoveGroupEntities : IDisposable
{
System.Data.Entity.DbSet<HostEntry> HostEntries { get; set; }
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
Task<int> SaveChangesAsync();
}
Then implemented the interface on a partial class which sits in conjunction with my generated entities like so:
public partial class MoveGroupEntities : IMoveGroupEntities
{
}
I have a sneaking suspicion I'm doing something incorrectly here as I feel like this line:
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
Shouldn't be needed, but it does appear to be necessary as "Entry" is used from within my scaffolded API controller.
Can anyone chime in here on a better way to achieve this?
The best you can say about scaffolded code is: it works. It's not the best code architecturally. I fully agree with the link you quote, but that doesn't mean that the controllers should be in touch with EF artifacts directly (including Entry).
I think it's a mistake to replace one DbSet wrapper (repository) by another wrapper. The gist of the answer is: use the context (and DbSets, etc.) directly in your code. That is: don't use wrappers. That is not: use contexts (etc.) anywhere. You're doing the exact opposite: you create a different type of wrapper in order to use EF anywhere. But it's a good thing that your gut feeling doesn't really like it.
I always prefer to keep action methods (MVC, Web API) small. Basically, I just make them call a service method. It's the service that deals with contexts and everything EF has to offer. These services may be in a separate assembly, but wherever they are, they are injected into the controllers by dependency injection and, likewise, they obtain their contexts by DI.

Resolve Views through IoC or MEF instead of using SelectedAssemblies() method

I use Caliburn.Micro with Spring.net instead of the default simple IoC. My custom Bootstrapper (derrived from Caliburn's BootstrapperBase) is working and I can define the ViewModels within Spring.net. But the the Views are still resolved by reflection (name convention) from the execution assembly. I used the following method of the Bootstrapper to add Assemblies for resolving the Views for the ViewModels.
protected override IEnumerable<Assembly> SelectAssemblies()
{
// hmm, want to change the way how the view is resolved... how to do this?
// ... use IoC or MEF for this task instead?
return new[]
{
// don't want to add every dll here
this.GetType().Assembly,
Assembly.Load("MyViewModels.Assembly")
};
}
How to change the behaviour of resolving views and using IoC or MEF for this task?
The Problem is that the Bootstrapper has no virtual method to override which resolves a requested view. What is the starting point to change this behaviour? I thought there must exist something like
protected virtual Control ResolveViewForModel(Type modelType) {...}
Thanks for any hints.
First of all, I don't know caliburn.micro so this might be wrong.
Looking at the ViewLocator method LocateTypeForModelType it seems that it asks the AssemblySource for available types which should be checked against the View-naming conventions.
Since all of the above are static classes I suspect there is no way to inherit and override that behaviour. Since they are static, one could just add assemblies to the public observable dictionary - which feels a little bit of a hack and SelectAssemblies seems like the proper way.
However, it seems to me that since there are conventions for resolving Views and ViewModels one could do the same for assemblies which brings us to the question: how do you decide which assemblies to scan for ViewModels/Views.
That strategy can be built into the SelectAssemblies method.
If you want to change how caliburn.micro finds the right views in those assemblies, effectively changing/adding to the exisiting conventions, there is an explanation in their wiki.
To finally answer your question: "Resolve Views through IoC or MEF instead of using SelectedAssemblies() method": Imo this kind of defeats the philosophy of Caliburn.Micro:
Caliburn.Micro uses conventions to resolve views from given assemblies - trying to use an IoC container instead of a name / namespace based convention contradicts that approach.

MVVM Dependency Injection

I'm in the process of teaching myself the MVVM pattern by dividing the pattern into its core facets and learning those facets one by one.
My question is related to dependency injection. What is it, and why/when should I use it? I've looked at Jason Dolinger's excellent MVVM intro video and I see he uses Unity. This might be strange to ask but how would I implement dependency injection WITHOUT using Unity? I basically want to understand the concept of dependency injection and how to use it without having to implement other frameworks/tools (for now).
Thanks.
I think it's good that you want to understand DI without using a framework, the concept is not terribly difficult to wrap your head around.
Let's say you want to use some form of transportation.
interface ITransportation
{
Transport();
}
An initial implementation of a method that uses a form of transportation might look like this:
public void Move()
{
ITransportation car = new Car();
car.Transport();
}
The problem with that method is that it is now dependent on a Car class. We should pass our transportation object in for added flexibility. This is inversion of control and is closely related to DI.
public void Move(ITransportation tr)
{
tr.Transport();
}
As you can see, we don't need to know anything about a specific DI framework. You might also want to check out the ninject DI by hand tutorial.
Just to extend #Andy's answer
Dependency Injection is one of the forms of the Dependency Inversion Principle
To achieve the decoupling of dependencies (as typically found in layered architecture),
DI is commonly used for instantiation scenarios such as basic new() and patterns like Factory method. In addition to being able to inject a new dependency instance every time (e.g. like factory), containers can also be set up to inject named instances, singleton instances, etc - i.e. IoC containers usually also take on the responsibility of managing the lifespans of objects as well.
One potential 'mindset shift' is that dependencies now potentially become publicly visible on concrete classes, since DI typically injects via constructors or public Get / Set properties. This may seem strange if you are used to using OO encapsulation, where dependencies of a class are seen as implementation and should be hidden from the 'outside' i.e. class method signatures.
However, by implementing Interface / Concrete class separation (as you should, not only for decoupling but also for testing / mocking purposes), the injection constructors / property injection methods will not be on the interface, so encapsulation is again in place.
Re : "Doing DI by hand" without Unity etc
What you would need to do is to code your own IoC container, which then is responsible for 'building up' instances of classes - during each 'build up', you would scan the class for dependencies (which are configured in the container, e.g. by config, by attributes, or simply just by convention, e.g. all public settable properties, or any class parameters on a constructor will be assumed to be dependencies). You would then create (if necessary) and inject this 'dependency' instance onto the object (e.g. by using reflection). And then recursively, all dependencies of these dependencies need to be built up etc. You would then also need to provide lifespan management for each of the objects, e.g. Singletons etc.

ViewModel -> Model: Who's responsible for persistance logic?

in my ASP MVC 2 application I follow the strongly typed view pattern with specific viewmodels.
Im my application viewmodels are responsible for converting between models and viewmodels. My viewmodels I have a static ToViewModel(...) function which creates a new viewmodel for the corresponding model. So far I'm fine with that.
When want I edit a model, I send the created viewmodel over the wire and apply the changes to back to the model. For this purpose I use a static ToModel(...) method (also declared in the view model). Here the stubs for clarification:
public class UserViewModel
{
...
public static void ToViewModel(User user, UserViewModel userViewModel)
{
...
}
public static void toModel(User user, UserViewModel userViewModel)
{
???
}
}
So, now my "Problem":
Some models are complex (more than just strings, ints,...). So persistence logic has to be put somewhere.(With persistence logic I mean the decisions wheater to create a new DB entry or not,... not just rough CRUD - I use repositories for that)
I don't think it's a good idea to put it in my repositories, as repositories (in my understanding) should not be concerned with something that comes from the view.I thought about putting it in the ToModel(...) method but I'm not sure if thats the right approach.
Can you give me a hint?
Lg
warappa
Warappa - we use both a repository pattern and viewmodels as well.
However, we have two additonal layers:
service
task
The service layer deals with stuff like persisting relational data (complex object models) etc. The task layer deals with fancy linq correlations of the data and any extra manipulation that's required in order to present the correct data to the viewmodel.
Outwith the scope of this, we also have a 'filters' class per entity. This allows us to target extension methods per class where required.
simples... :)
In our MVC projects we have a seperate location for Converters.
We have two types of converter, an IConverter and an ITwoWayConverter (a bit more too it than that but I'm keeping it simple).
The ITwoWayConverter contains two primary methods ConvertTo and ConvertFrom which contain the logic for converting a model to a view model and visa versa.
This way you can create specific converts for switching between types such as:
public class ProductToProductViewModelConverter : ITwoWayConverter<Product,ProductViewModel>
We then inject the relevant converters into our controller as needed.
This means that your conversion from one type to another is not limited by a single converter (stored inside the model or wherever).

Inversion of Control, Dependency Injection w/SRP, and Lazy-Loading

A fellow developer and I are conversing (to put it lightly) over Lazy-Loading of Properties of an object.
He says to use a static IoC lookup call for resolution and Lazy-Loading of objects of an object.
I say that violates SRP, and to use the owning Service to resolve that object.
So, how would you handle Lazy-Loading following IoC and SRP?
You cannot Unit test that lazy-loaded property. He rebuttles that one saying, "you already have unit tests for the UserStatsService - there's your code coverage." A valid point, but the property remains untested though for "complete" coverage.
Setup / code patterns:
Project is using strict Dependency Injection rules (injected in the ctors of all services, repositories, etc).
Project is using IoC by way of Castle (but could be anything, like Unity).
An example is below.
public class User
{
public Guid UserId { get; set; }
private UserStats _userStats;
// lazy-loading of an object on an object
public UserStats UserStats
{
get
{
if (_userStats == null)
{
// ComponentsLookup is just a wrapper around IoC
// Castle/Unity/etc.
_userStats =
ComponentsLookup
.Fetch<UserStatsService>()
.GetByUserId(this.UserId);
}
return _userStats;
}
}
}
The above shows an example of lazy-loading an object. I say not to use this, and to access UserStatsService from the UI layer wherever you need that object.
EDIT: One answer below reminded me of the NHibernate trick to lazy-loading, which is to virtualize your property, allowing NHibernate to create an over-load of the lazy-loading itself. Slick, yes, but we are not using NHibernate.
No one really tackles the matter of Lazy-Loading. Some good articles and SO questions get close:
Using Dependency Injection frameworks for classes with many dependencies
http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx
I do see a benefit of lazy-loading. Don't get my wrong, all I did was lazy-loading of my complex types and their sub-types until I switched to the D.I.-ways of the ninja. The benefit is in the UI layer, where a user's stats is displayed, say, in a list with 100 rows. But with DI, now you have to reference a few lines of code to get that user stats (to not violate SRP and not violate the law-of-Demeter), and it has to walk this long path of lookups 100+ times.
Yes yes, adding caching and ensuring the UserStatsService is coded to be used as a Singleton pattern greatly lower the performance cost.
But I am wondering if anyone else out there has a [stubborn] developer that just won't bend to the IoC and D.I. rules completely, and has valid performance/coding points to justify the work-arounds.
Entities themselves should not have the responsibility of lazy loading. That is an infrastructural concern whose solution will lie elsewhere.
Let's say an entity is used in two separate contexts. In the first, its children are used heavily and are eagerly-loaded. In the second, they are used rarely and are lazy-loaded. Is that also the entity's concern? What would the configuration look like?
NHibernate answers these questions by proxying the entity type. A property of type IList<Entity> is set by the infrastructure to an implementation which knows about lazy loading. The entity remains blissfully unaware. Parent references (like in your question) are also handled, requiring only a simple property.
Now that the concern is outside the entity, the infrastructure (ORM) is responsible for determining context and configuration (like eager/lazy loading).