ASP.NET Core - Add Custom Property to HttpRequest - c#

I have some ASP.NET Middleware that analyzes a request as it comes in. Based on what's available in that HttpRequest, I would like to add a custom property that I can use in my code. My question is, is there a way for me to add a property to HttpRequest so that I can access it in my controller? For example, in my Controller, I would like to do something like this:
namespace MyWebsite.Controllers
{
public class MyController : Controller
public IActionResult Index()
{
if (this.Request.MyProperty == null)
{
return View("~/Views/NoExist.cshtml");
}
return View ("/Views/Index.cshtml");
}
}
MyProperty represents the custom property that I would like to inject, or add, via my custom middleware. Is this possible? If so, how? If not, what is the recommended approach?
Thank you!

The traditional way of achieving what you want is sharing everything via HttpContext.Items. That way you should manage the keys yourself or even can declare your extension methods for conveniently setting & getting the values.
However here I'd like to introduce a new way associated with a new concept request feature in asp.net core. The features associated with each request can be added by different middlewares along the pipeline and can be consumed by any (if available). That looks like neater and more organized, although may not be very convenient compared to the old way.
Suppose you're in the context of your middleware, the following code will add a feature which exposes your property:
//declare the feature interface first
public interface IMyFeature {
string MyProperty {get;}
}
//the concrete type for the feature
public class MyFeature : IMyFeature {
public MyFeature(string myProperty){
MyProperty = myProperty;
}
public string MyProperty {get;}
}
//the context is in your middleware
//add the feature
var myFeature = new MyFeature("value of your choice");
//context here is the HttpContext
context.Features.Set<IMyFeature>(myFeature);
Now anywhere later in the pipeline, you can consume the feature added like this:
//context here is the HttpContext
var myFeature = context.Features.Get<IMyFeature>();
if(myFeature != null){
//consume your feature
}
One point I think the request features concept is good about is its clear definition of feature interfaces which can be learned, referenced and managed easily by your code. Even porting it to some library for reusing makes more sense than depending on some constant key for accessing the shared data (as achieved by using HttpContext.Items). Of course for some simple data sharing, you can just use HttpContext.Items, the request feature should be used when it may evolve later, has a clear cool concept around it and may contain more data.

Create a singleton that has a readonly ConcurrentDictionary property. Alternatively, create a static class with a readonly static property of type ConcurrentDictionary.
Add a readonly Queue property to your global class.
Use the HttpContext.TraceIdentifier as a unique key and add
the data to the ConcurrentDictionary as the value. Also add the HttpContext.TraceIdentifier and DateTime.Now to the Queue property.
Create a clean-up method that removes old data from the Queue and ConcurrentDictionary by pulling data off the Queue until it is under a particular age, say 90 seconds.
Create a background worker that runs periodically and calls the cleanup method. There are libraries that do this. You can also spin off a thread at startup, but this lacks redundancy unless you code it.
Access your data from any called code using the key HttpContext.TraceIdentifier.
Happy Coding!

Related

C# how to "register" class "plug-ins" into a service class?

Update#2 as of year 2022
All these years have passed and still no good answer.
Decided to revive this question.
I'm trying to implement something like the idea I'm trying to show with the following diagram (end of the question).
Everything is coded from the abstract class Base till the DoSomething classes.
My "Service" needs to provide to the consumer "actions" of the type "DoSomethings" that the service has "registered", at this point I am seeing my self as repeating (copy/paste) the following logic on the service class:
public async Task<Obj1<XXXX>> DoSomething1(....params....)
{
var action = new DoSomething1(contructParams);
return await action.Go(....params....);
}
I would like to know if there is anyway in C# to "register" all the "DoSomething" I want in a different way? Something more dynamic and less "copy/paste" and at the same time provide me the "intellisense" in my consumer class? Somekind of "injecting" a list of accepted "DoSomething" for that service.
Update#1
After reading the sugestion that PanagiotisKanavos said about MEF and checking other options of IoC, I was not able to find exactly what I am looking for.
My objective is to have my Service1 class (and all similar ones) to behave like a DynamicObject but where the accepted methods are defined on its own constructor (where I specify exactly which DoSomethingX I am offering as a method call.
Example:
I have several actions (DoSomethingX) as "BuyCar", "SellCar", "ChangeOil", "StartEngine", etc....
Now, I want to create a service "CarService" that only should offer the actions "StartEngine" and "SellCar", while I might have other "Services" with other combination of "actions". I want to define this logic inside the constructor of each service. Then, in the consumer class, I just want to do something like:
var myCarService = new CarService(...paramsX...);
var res1 = myCarService.StartEngine(...paramsY...);
var res2 = myCarService.SellCar(...paramsZ...);
And I want to offer intellisense when I use the "CarService"....
In conclusion: The objective is how to "register" in each Service which methods are provided by him, by giving a list of "DoSomethingX", and automatically offer them as a "method"... I hope I was able to explain my objective/wish.
In other words: I just want to be able to say that my class Service1 is "offering" the actions DoSomething1, DoSomething2 and DoSomething3, but with the minimum lines as possible. Somehow the concept of the use of class attributes, where I could do something similar to this:
// THEORETICAL CODE
[RegisterAction(typeOf(DoSomething1))]
[RegisterAction(typeOf(DoSomething2))]
[RegisterAction(typeOf(DoSomething3))]
public class Service1{
// NO NEED OF EXTRA LINES....
}
For me, MEF/MAF are really something you might do last in a problem like this. First step is to work out your design. I would do the following:
Implement the decorator design pattern (or a similar structural pattern of your choice). I pick decorator as that looks like what you are going for by suplimenting certain classes with shared functionality that isn't defined in those clases (ie composition seems prefered in your example as opposed to inheritance). See here http://www.dofactory.com/net/decorator-design-pattern
Validate step 1 POC to work out if it would do what you want if it was added as a separate dll (ie by making a different CSProj baked in at build time).
Evaluate whether MEF or MAF is for right for you (depending on how heavy weight you want to go). Compare those against other techniques like microservices (which would philosophically change your current approach).
Implement your choice of hot swapping (MEF is probably the most logical based on the info you have provided).
You could use Reflection.
In class Service1 define a list of BaseAction types that you want to provide:
List<Type> providedActions = new List<Type>();
providedActions.Add(typeof(DoSomething1));
providedActions.Add(typeof(DoSomething2));
Then you can write a single DoSomething method which selects the correct BaseAction at run-time:
public async Task<Obj1<XXXX>> DoSomething(string actionName, ....params....)
{
Type t = providedActions.Find(x => x.Name == actionName);
if (t != null)
{
var action = (BaseAction)Activator.CreateInstance(t);
return await action.Go(....params....);
}
else
return null;
}
The drawback is that the Client doesn't know the actions provided by the service unless you don't implement an ad-hoc method like:
public List<string> ProvidedActions()
{
List<string> lst = new List<string>();
foreach(Type t in providedActions)
lst.Add(t.Name);
return lst;
}
Maybe RealProxy can help you? If you create ICarService interface which inherits IAction1 and IAction2, you can then create a proxy object which will:
Find all the interfaces ICarService inherits.
Finds realizations of these interfaces (using actions factory or reflection).
Creates action list for the service.
In Invoke method will delegate the call to one of the actions.
This way you will have intellisence as you want, and actions will be building blocks for the services. Some kind of multi-inheritance hack :)
At this point I am really tempted to do the following:
Make my own Class Attribute RegisterAction (just like I wrote on my "Theoretical" example)
Extend the Visual Studio Build Process
Then on my public class LazyProgrammerSolutionTask: Microsoft.Build.Utilities.Task try to find the service classes and identify the RegisterAction attributes.
Then per each one, I will inject using reflection my own method (the one that I am always copying paste)... and of course get the "signature" from the corresponding target "action" class.
In the end, compile everything again.
Then my "next project" that will consume this project (library) will have the intellisence that I am looking for....
One thing, that I am really not sure, it how the "debug" would work on this....
Since this is also still a theoretically (BUT POSSIBLE) solution, I do not have yet a source code to share.
Meanwhile, I will leave this question open for other possible approaches.
I must disclose, I've never attempted anything of sorts so this is a thought experiment. A couple of wild ideas I'd explore here.
extension methods
You could declare and implement all your actions as extension methods against base class. This I believe will cover your intellisense requirements. Then you have each implementation check if it's registered against calling type before proceeding (use attributes, interface hierarchy or other means you prefer). This will get a bit noisy in intellisense as every method will be displayed on base class. And this is where you can potentially opt to filter it down by custom intellisense plugin to filter the list.
custom intellisense plugin
You could write a plugin that would scan current code base (see Roslyn), analyze your current service method registrations (by means of attributes, interfaces or whatever you prefer) and build a list of autocomplete methods that apply in this particular case.
This way you don't have to install any special plugins into your Dev environment and still have everything functional. Custom VS plugin will be there purely for convenience.
If you have a set of actions in your project that you want to invoke, maybe you could look at it from CQS (Command Query Separation) perspective, where you can define a command and a handler from that command that actually performs the action. Then you can use a dispatcher to dispatch a command to a handler in a dynamic way. The code may look similar to:
public class StartEngine
{
public StartEngine(...params...)
{
}
}
public class StartEngineHandler : ICommandHandler<StartEngine>
{
public StartEngineHandler(...params...)
{
}
public async Task Handle(StartEngine command)
{
// Start engine logic
}
}
public class CommandDispatcher : ICommandDispatcher
{
private readonly Container container;
public CommandDispatcher(Container container) => this.container = container;
public async Task Dispatch<T>(T command) =>
await container.GetInstance<ICommandHandler<T>>().Handle(command);
}
// Client code
await dispatcher.Dispatch(new StartEngine(params, to, start, engine));
This two articles will give you more context on the approach: Meanwhile... on the command side of my architecture, Meanwhile... on the query side of my architecture.
There is also a MediatR library that solves similar task that you may want to check.
If the approaches from above does not fit the need and you want to "dynamically" inject actions into your services, Fody can be a good way to implement it. It instruments the assembly during the build after the IL is generated. So you could implement your own weaver to generate methods in the class decorated with your RegisterAction attribute.

Attach an object to the pipeline without DI on ASP.NET 5 (or extending HttpContext)

tl;dr
.- Is there a way to include a property (extend) on the HttpContext of a custom class, the same as there's a User property which is a ClaimsPrincipal? I want to access HttpContext.MyOwnProperty of a custom class along all the pipeline (without DI).
Long explanation:
I've created my own identity system on ASP.NET 5 to get rid of the framework's umpteenth and ever-changing Identity System, of which I'm really tired of, and to get away of the use of claims, which could be very standardized but are also inefficient where you come to lot of them.
I use a typed object for representing a user access, and obtain it from an in memory (or from a shared caché) repository which is a service registered early on the pipeline, somehow as the current UserManager. Then I pass this object to the pipeline by means of mapping it's properties to a scoped service that I've registered previously:
services.AddSingleton<AccessManager>();
services.AddScoped<CurrentAccess>();
Everything is working fine but I'm wondering if there would be a more efficient way to attach the CurrentAccess object to the pipeline, other than having to inject and resolve it on every place, since it's broadly used in the application.
The goal is to extend the HttpContext class to add a property of the CurrentAccess type, the same as there is a User property wich is a ClaimsPrincipal. That would be great, but I don't know how to do it. Any idea out there?
(I've also tried another approach that is using the HttpContext.Items property, which is a Dictionary<object, object> where I can add my own object, but I don't know it's lifecycle and I would have to look for my item and cast it every time, what seems uglier than the previous option)
Keep registering your services the same way you are doing.
services.AddSingleton<AccessManager>();
services.AddScoped<CurrentAccess>();
Then create an HttpContext.GetCurrentAccess extension method that returns the CurrentAccess object:
public static class HttpContextExtensions
{
public static CurrentAccess GetCurrentAccess(this HttpContext httpContext)
{
return httpContext.RequestServices.GetRequiredService<CurrentAccess>();
}
}
This way, you can use the extension method as a convenience method in places where you don't want to a CurrentAccess dependency to be injected in the constructor.
public IActionResult Index()
{
var currentAccess = this.Context.GetCurrentAccess();
...
return View();
}
Where makes sense to take a dependency take it, in other places use the convenience extension method.
Is there a way to include a property (extend) on the HttpContext of a custom class, the same as there's a User property wich is a ClaimsPrincipal? I want to access HttpContext.MyOwnProperty of a custom class along all the pipeline (without DI).
You can't add properties to a class. That would be an awesome C# feature though :).

Attempting to generalize a authentication (Including parameter changing)

In our MVC project we are attempting to make everything as generic as possible.
Because of this we want to have one authentication class/method which covers all our methods.
As a example: The following code is a MVC class which can be called to from a client
public class Test
{
public void Test()
{
}
public int Test2(int i)
{
return i
}
public void Test3(string i)
{
}
}
A customer of our webservice can use a service reference to get access to Test(), Test2() and Test3().
Now i'm searching for a class, model, interface or anything else which I can use to alter the access to the method (Currently using [PrincipalPermission] attribute) as well as alter the parameter value.
Example:
Customer A calls Test2(150)
The class/method checks whether Customer A has access to Test2. The class/method validates the user but notices that the user does not have access to 150. He only has access to 100.So the class/method sets the parameter to 100 and lets it follow through on it's journey.
Customber B class Test()
The class/method checks whether Customer B has access to Test. After validation it shows that the user does not have access so it throws a SecurityException.
My question:
In what class, interface, attribute or whatever can I best do this?
(ps. As example i've only used authentication and parameter handling, but we plan to do a lot more in this stage.)
Edit
I notice most, if not all, assume I'm using actionResults. So i'd like to state that this is used in a webservice where we provide our customers with information from our database. In no way will we come in contact with a ActionResult during the requests to our webservice. (Atleast, not our customers)
Authentication can also be done through an aspect. The aspect oriented paradigm is designed to honor those so-called cross-cutting concerns. Cross-cutting concerns implemented in the "old-fashioned" oo-way make your business logic harder to read (like in Nick's example above) or even worse to understand, because they don't bring any "direct" benefit to your code:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
The only thing you want here is /* the rest of your code */ and nothing more.
Stuff like logging, exception handling, caching and authorization for example could be implemented as an aspect and thus be maintained at one single point.
PostSharp is an example for an aspect-oriented C# framework. With PostSharp you could create a custom aspect and then annotate your method (like you did with the PrincipalPermissionAttribute). PostSharp will then weave your aspect code into your code during compilation. With the use of PostSharp aspects it would be possible to hook into the method invocation authenticating the calling user, changing method parameters or throw custom exceptions (See this blog post for a brief explanation how this is implemented).
There isn't a built-in attribute that handles this scenario.
I find it's usually best to just do something like this:
public ActionResult YourAction(int id) {
if (!CustomerCanAccess(id)) {
return new HttpUnauthorizedResult();
}
/* the rest of your code */
}
This is as simple as it gets and easy to extend. I think you'll find that in many cases this is all you need. It also keeps your security assertions testable. You can write a unit test that simply calls the method (without any MVC plumbing), and checks whether the caller was authorized or not.
Note that if you are using ASP.Net Forms Authentication, you may also need to add:
Response.SuppressFormsAuthenticationRedirect = true;
if you don't want your users to be redirected to the login page when they attempt to access a resource for which they are not authorized.
Here's how I've made my life simpler.
Never use simple values for action arguments. Always create a class that represents the action arguments. Even if there's only one value. I've found that I usually end up being able to re-use this class.
Make sure that all of teh properties of this class are nullable (this keeps you from running into default values (0 for integers) being automatically filles out) and thatallowable ranges are defined (this makes sure you don't worry about negative numbers)
Once you have a class that represents your arguments, throwing a validator onto a property ends up being trivial.
The thing is that you're not passing a meaningless int. It has a purpose, it could be a product number, an account number, etc. Create a class that has that as a property (e.g An AccountIdentifier class with a single field called 'id). Then all you have to do is create a [CurrentUsedCanAccessAccountId] attribute and place it on that property.
All your controller has to do is check whether or not ModelState.IsValid and you're done.
There are more elegant solutions out there, such as adding an action filter to the methods that would automatically re-direct based on whether or not the user has access to a specific value for the parameter, but this will work rather well
First, just to say it, that your own methods are probably the most appropriate place to handle input values (adjust/discard) - and with the addition of Authorize and custom filter actions you can get most done, and the 'MVC way'. You could also go the 'OO way' and have your ITest interface, dispatcher etc. (you get more compiler support - but it's more coupled). However, let's just presume that you need something more complex...
I'm also assuming that your Test is a controller - and even if it isn't it can be made part of the 'pipeline' (or by mimicking what MVC does), And with MVC in mind...
One obvious solution would be to apply filters, or action filters via
ActionFilterAttribute
Class
(like Authorize etc.) - by creating your own custom attribute and
overriding OnActionExecuting etc.
And while that is fine, it's not going to help much with parameters manipulation as you'd have to specify the code 'out of place' - or somehow inject delegates, lambda expressions for each attribute.
It is basically an interceptor of some sort that you need - which allows you to attach your own processing. I've done something similar - but this guy did a great job explaining and implementing a solution - so instead of me repeating most of that I'd suggest just to read through that.
ASP.NET MVC controller action with Interceptor pattern (by Amar, I think)
What that does is to use existing MVC mechanisms for filters - but it exposes it via a different 'interface' - and I think it's much easier dealing with inputs. Basically, what you'd do is something like...
[ActionInterceptor(InterceptionOrder.Before, typeof(TestController), "Test1")]
public void OnTest1(InterceptorParasDictionary<string, object> paras, object result)
The parameters and changes are propagated, you have a context of a sort so you can terminate further execution - or let both methods do their work etc.
What's also interesting - is the whole pattern - which is IOC of a
sort - you define the intercepting code in another class/controller
all together - so instead of 'decorating' your own Test methods -
attributes and most of the work are placed outside.
And to change your parameters you'd do something like...
// I'd create/wrap my own User and make this w/ more support interfaces etc.
if (paras.Count > 0 && Context.User...)
{
(paras["id"] as int) = 100;
}
And I'm guessing you could further change the implementation for your own case at hand.
That's just a rough design - I don't know if the code there is ready for production (it's for MVC3 but things are similar if not the same), but it's simplistic enough (when explained) and should work fine with some minor adjustments on your side.
I'm not sure if I understood your question, but it looks like a model binder can help.
Your model binder can have an interface injected that is responsible for determining if a user has permissions or not to a method, and in case it is needed it can change the value provided as a parameter.
ValueProviders, that implement the interface IValueProvider, may also be helpful in your case.
I believe the reason you haven't gotten ay good enough answer is because there are a few ambiguities in your question.
First, you say you have an MVC class that is called from a client and yet you say there are no ActionResults. So you would do well to clarify if you are using asp.net mvc framework, web api, wcf service or soap (asmx) web service.
If my assumption is right and you are using asp.net mvc framework, how are you defining web services without using action results and how does your client 'call' this service.
I am not saying it is impossible or that what you may have done is wrong, but a bit more clarity (and code) would help.
My advice if you are using asp.net mvc3 would be to design it so that you use controllers and actions to create your web service. all you would need to do would be to return Json, xml or whatever else your client expects in an action result.
If you did this, then I would suggest you implement your business logic in a class much like the one you have posted in your question. This class should have no knowledge of you authentication or access level requirements and should concentrate solely on implementing the required business logic and producing correct results.
You could then write a custom action filter for your action methods which could inspect the action parameter and determine if the caller is authenticated and authorized to actually access the method. Please see here for how to write a custom action filter.
If you think this sounds like what you want and my assumptions are correct, let me know and I will be happy to post some code to capture what I have described above.
If I have gone off on a tangent, please clarify the questions and we might be one step closer to suggesting a solution.
p.s. An AOP 'way of thinking' is what you need. PostSharp as an AOP tool is great, but I doubt there is anything postsharp will do for you here that you cannot achieve with a slightly different architecture and proper use of the features of asp.net mvc.
first create an attribute by inheriting from ActionFilterAttribute (system.web.mvc)
then override OnActionExecuting method and check if user has permission or not
this the example
public class CheckLoginAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!Membership.IslogedIn)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "area",""},
{ "action", "login" },
{ "controller", "user" },
{ "redirecturl",filterContext.RequestContext.HttpContext.Request.RawUrl}
});
}
}
}
and then, use this attribute for every method you need to check user permission
public class Test
{
[ChecklLogin]
public void Test()
{
}
[ChecklLogin]
public int Test2(int i)
{
return i
}
[ChecklLogin]
public void Test3(string i)
{
}
}

Override WebConfigurationManager.AppSettings["SomeProperty"] dynamically during execution

I have a code like that:
// can't make any changes at that class
class MyClass
{
void SomeMethod()
{
// some code ...
var someVar = WebConfigurationManager.AppSettings["SomeProperty"];
// some code ...
}
}
I can't change that code, but I need that WebConfigurationManager.AppSettings["SomeProperty"] return different values depending on some external conditions (for example, depending on user role). So I'm looking for some way to override accessing to that property. In that override method I would check user role and
return appropriate value.
Is there any way to do that?
I found that question: Is there a way to override ConfigurationManager.AppSettings? but it seems that it's not suitable for me, because here value of WebConfigurationManager.AppSettings["SomeProperty"] set once when application starts. And I need to do it dynamically.
In MVC, in order to simplify the testing and mocking, I tend to use customized object for all the common classes, like Request, Session and ConfigManager, referenced through interfaces.
You basically don't need to realize classes from scratch obviously, so your implementation can be a wrapper which is actually using the .net class under the hood, but which gives also the chance to insert some custom logic in the middle, like in your case.
Therefore, you can create a wrapper of the webconfigurationManager, with a method like GetAppConfig(key) containing your own logic.
Playing with the concept of dependency injection is then easy enough having this class available wherever you need it.
Therefore to make a simple example:
//this will be injected
public MyControllerCtor(IConfig cfg)
public interface IConfig
{
string GetAppConfig(string key);
}
public class myConfig:IConfig
{
public string GetAppConfig(string key)
{
//your logic
var someVar = WebConfigurationManager.AppSettings["SomeProperty"];
//your logic
return yourCustomAppSetting;
}
}
Big advantage of this approach is that if you wanted to store your config in a database or a service, and change your code, you simply need to change your interface implementation and the inject the new instance.
If you can't change the code that is reading the AppSettings, then there is no way to do what you want. WebConfigurationManager is not pluggable or replacable externally.
You'll have to change the code.
No, of course not.
If you can't change the class, then you can't change the behavior. There's no general reason why Microsoft would have placed an "override" capability inside of WebApplicationManager. Usually, one is expected to be able to change ones class, or else to design it properly so that it can be overridden the right way.
It sounds like you need to do some logic after retrieving the value from the web.config. If the logic modifies the value itself, you could always store a format string in the web.config instead.
Here's an example using a connection string setting. I'm using a format string to populate the server name at runtime:
<add name="sqlconnection" connectionString="Server={0}\SQLEXPRESS;Database=xxx;Trusted_Connection=True;"/>
And then I'm using this logic:
string connect = ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
if (!String.IsNullOrEmpty(connect))
{
//check to see if the connection string needs to be set at runtime
if (connect.Contains("{0}"))
connect = String.Format(connect, HttpContext.Current.Server.MachineName);
}
return connect;
EDIT: If you can't edit the class directly, I would consider creating a partial class to implement this.
If you make direct changes to Web.config they will be effective only during the next request, and as I understand, this is not the desired effect.
You can not directly affect WebConfigurationManager.AppSettings["SomeProperty"], and that's the desired behavior, as the AppSettings as configurations are something static.
To achieve an effect close to what you desire, I'd suggest you to use the HttpContext.Current.Items collection, in which you will initialize in Application_BeginRequest to a certain value if conditions are met or default to WebConfigurationManager.AppSettings["SomeProperty"] otherwise.
Than, instead of accessing WebConfigurationManager.AppSettings["SomeProperty"] you will be accessing HttpContext.Current.Items["SomeProperty"].

Get information about the decorated member by an attribute in C#

I need to know if there's any way (or another distinct approach) to an attribute knows something about what is being decorated for him. For example:
class Cat
{
public Cat() { }
[MyAttribute]
public House House { get; set; }
}
Inside MyAttribute I must do some preprocessing with the house object...
class MyAttribute : Attribute
{
public MyAttribute()
{
var ob = // Discover the decorated property, do some changes and set it again
}
}
I don't know if it's the better way, neither if it actually can be done,
This is not how attributes work. They are just compile time metadata added to something. They don't accomplish anything by themselves. At runtime, code can use that metadata to do things.
UPDATE: Basically, as I understand, you are trying to accomplish two things. The first is to tell the repository not to load some properties. Attributes can be used for this purpose but the repository code should use reflection on the entity type and see what it shouldn't load in the first place. The second thing is that you want to have the property loaded as it's called for the first time. You need to check if it's already loaded or not on each call and load it the first time it's called. This can be achieved by manually inserting such a code or using something like PostSharp which post-processes code and can inject method calls automatically by looking at the attributes. Probably, this is what you asked for in the first place.
What you want is the Policy Injection application block in EntLib.
Developers can use the Policy
Injection Application Block to specify
crosscutting behavior of objects in
terms of a set of policies. A policy
is the combination of a series of
handlers that execute when client code
calls methods of the class and—with
the exception of attribute-based
policies—a series of matching rules
that select the classes and class
members (methods and properties) to
which the application block attaches
the handlers.

Categories

Resources