Using autofac to inject properties into asp.net pages: Overriding PropertyInjectionModule behaviour to inject values/settings - asp.net

Is it possible to inject values/settings into ASP.NET Pages via autofac's PropertyInjectionModule? I get the impression that default handler behavior is to search for properties and find any types that match services in the container.
eg for a page:
public class MyPage: System.Web.UI.Page {
public IDataProvider DataProvider { get; set; }
public bool SomeSetting {get; set; }
public bool AnotherSetting { get; set; }
public string MySettings { get; set; }
// stuff
}
I thought maybe you could specify properties:
builder.RegisterType<MyPage>()
.WithProperty("SomeSetting", true)
.WithProperty("AnotherSetting", false)
.WithProperty("MySettings", "do-re-mi");
but it doesn't seem to work.
I realise I could setup an IMyPageConfig interface and provide settings that way but these are optional properties that may or may not need to be set.

IoC in ASP.NET Pages is a bit limited - although the module is injecting properties into the page, it can't really use Autofac's regular dependency injection features.
In WebForms the way people typically get around this is to use something like Model-View-Presenter, where the page is just a 'dumb' view and the presenter is where the logic (and proper dependency injection) takes place.
Check out http://webformsmvp.com/ - I think there is an IoC example and Autofac support available there.

Related

How to decouple MediatR from my business layer

Good morning.
I'm using domain events in my project, and the easiest way i found to implement it was by using MediatR.
But i don't want my project to directly depend on it, i want apply dependency inversion to hide the library.
Current code that has a dependency in Mediator, because of INotification interface
public class EmailConfirmedEvent : INotification
{
public Guid PassengerId { get; }
public string Email { get; }
public EmailConfirmedEvent(Guid passengerId, string email)
{
Email = email;
PassengerId = passengerId;
}
}
But i want to be like this:
public class EmailConfirmedEvent : IMyProjectDomainEvent
{
public Guid PassengerId { get; }
public string Email { get; }
public EmailConfirmedEvent(Guid passengerId, string email)
{
Email = email;
PassengerId = passengerId;
}
}
By some way i'll need to "convert" from mediator events/event handlers to my project events/event handlers.
What's the best way to do this.
Thanks in advance.
I ended up creating my domain event custom code using StructureMap and reflection to resolve the event handlers at runtime.
Code sample here: https://github.com/Henry-Keys/domain-events-sample
I generally make base classes that inherit from MediatR interfaces/base. Then if you change libraries (unlikely) you just have to update the base classes and the rest of the implement remains untouched.

Dependency Injection into a AuthorizationFilterAttribute

I am pretty new to Unity & IoC in general & as usual, I have quickly got myself into a bind...
I have created an Authorization Filter Attribute for the ASP.NET Web API Beta. I now need to inject my Authorizer into the Attribute however since this is an attribute I cannot simply do this public TestAuthAttribute(IAuthorizer Authorizer) in my constructor.
So I then decided to create a public property decorated with the [Dependency] attribute for property injection however it does not get resolved.
Here is the code:
public class TestAuthAttribute : AuthorizationFilterAttribute
{
[Dependency]
public IAuthorizer Authorizer { get; set; }
public TestAuthAttribute() {
...
}
private bool authorizeCore(HttpRequestMessage request)
{
if (Authorizer == null)
throw Error.ArgumentNull("Null Authorizer"); // <<<<< this is null
}
When the controller is decorated with the [TestAuth] the Attribute is triggered but the Authorizer is not resolved, it is null)
I have placed the following code in my controller & Authorizer does get resolved...
[Dependency]
public IAuthorizer Authorizer { get; set; }
Why is this dependency not resolved in my AuthorizationFilterAttribute & how would you go about Injecting the Authorizer into the AuthorizationFilterAttribute?
Full disclosure: I have not used Turbine.
Having said that, I think it might solve your problem for you or at least show you how to solve it.
They have a Unity Nuget package here: http://nuget.org/packages/MvcTurbine.Unity
And you can find more detail on their codeplex site here: http://mvcturbine.codeplex.com/
Hope that helps.
I use Ninject for similar purpose. I do have a reference to Ninject.Web.WebAPI which works perfectly.
However, this does not seem working with MVC4 RC.

Overriding validation attribute from a base Model

i have a MVC controller called MyController with an action called MyAction. For other hand i have a Model called MyModel, and all this classes are in a project called Portal.Website (Asp.net MVC3 Application) that i use as a generic website and that store common functionalities for custom websites that i will add in the future.
For other hand i have another website project with a reference to Portal.Website project called Portal.Website.MyCustomWebsite.
This is the viewmodel MyModel.cs in the generic website part:
namespace Portal.Website
{
public class MyModel
{
[Required(ErrorMessage="The field Name is required.")]
[Display("MyPropertyOriginal")]
public virtual string Name{get;set;}
}
}
This is the controller and action in the generic website part:
namespace Portal.Website
{
public class MyController: Controller
{
[HttpPost]
public ActionResult MyAction(MyModel model)
{
if(Model.IsValid)
....
//My issue: Im getting the error message in english, not the overridden one.
}
}
}
This is the viewmodel that i created in the custom part:
namespace Portal.Website.MyCustomWebsite
{
public class MyModel: MyModel
{
[Required(ErrorMessage="My error message in other language.")]
[Display("MyPropertyOverriden")]
public override string Name{get;set;}
}
}
My problem:
I would like to override the ErrorMessage of the Required attribute. For this reason i created a new Model in my custom project. For other hand i would like to use the Controller/Action (MyController/MyAction) that is already defined in my common part.
Do you know if this is possible? Im only getting the issue with the Required attribute, but with the Display one its working perfect.
Thanks in advance.
Greets.
Jose.
You may want to check out this article that suggests two possible solutions :
http://www.codeproject.com/Articles/130586/Simplified-localization-for-DataAnnotations
I've found it was making more sense to re-create some DataAnnotation classes with my custom logic.
MVC3 comes with better support for I18N (internationalisation) than it's predecessors - you can pass the RequiredAttribute the type of your resource class and the resource key and the error message will be displayed in whichever language is most appropriate:
[Required(ErrorMessageResourceType = typeof(MyResources), ErrorMessageResourceName = "ResourceKey")]
public override string Name { get; set; }

During JSON Serialization in .NET, is there a way to specify how "deep" the object graph you wish to go?

I have some complex object graphs, when I want to send them down to the client, I'm creating a separate DTO and serializing the objects into that. This is a pain in the ass. Is there anyway to serialize objects and only say, "Go one references deep" so if I have an object:
public class Test {
public Project { get; set; }
}
public class Project {
public int Id { get; set; }
public Vendor Vendor { get; set; }
}
If I go to serialize Test it won't go to the Vendor, but it'll correctly serialize the Project. I realize I can add an annotation for JsonIgnore, but if I were serializing all Projects, I might want a Vendor.
I think you're going to have to do some custom extension work: I found a conversation and some samples at http://json.codeplex.com/Thread/View.aspx?ThreadId=24459

Configuration and Views

I've been developing an application using asp.net MVC, and I have some configurations that influences in process of render a view. For example, a user can choose (in an configuration of system) if a field should appear for a management of records in an area of the system. So, I have an class called AppConfiguration has some properties to represent this configurations.
I guess I need to cache an object of AppConfiguration, and make a ViewModel base class and inherits from my viewmodel, for example:
public class BaseViewModel {
public AppConfiguration Config { get; set; }
}
public class DocumentViewModel : BaseViewModel {
public Document Document { get; set; }
}
and make typed views using "DocumentViewModel" to check the properties if this kind of document is able to render or not ? is it works ? Or is there any other better way to do something like this ?
Thanks all and sorry for my english!
Cheers
I'd suggest that you write an associated metadata provider for your view model and then use default templated views in MVC 2.

Resources