Where to store data for current WCF call? Is ThreadStatic safe? - wcf

While my service executes, many classes will need to access User.Current (that is my own User class). Can I safely store _currentUser in a [ThreadStatic] variable? Does WCF reuse its threads? If that is the case, when will it clean-up the ThreadStatic data? If using ThreadStatic is not safe, where should I put that data? Is there a place inside OperationContext.Current where I can store that kind of data?
Edit 12/14/2009: I can assert that using a ThreadStatic variable is not safe. WCF threads are in a thread pool and the ThreadStatic variable are never reinitialized.

There's a blog post which suggests implementing an IExtension<T>. You may also take a look at this discussion.
Here's a suggested implementation:
public class WcfOperationContext : IExtension<OperationContext>
{
private readonly IDictionary<string, object> items;
private WcfOperationContext()
{
items = new Dictionary<string, object>();
}
public IDictionary<string, object> Items
{
get { return items; }
}
public static WcfOperationContext Current
{
get
{
WcfOperationContext context = OperationContext.Current.Extensions.Find<WcfOperationContext>();
if (context == null)
{
context = new WcfOperationContext();
OperationContext.Current.Extensions.Add(context);
}
return context;
}
}
public void Attach(OperationContext owner) { }
public void Detach(OperationContext owner) { }
}
Which you could use like that:
WcfOperationContext.Current.Items["user"] = _currentUser;
var user = WcfOperationContext.Current.Items["user"] as MyUser;

An alternative solution without adding extra drived class.
OperationContext operationContext = OperationContext.Current;
operationContext.IncomingMessageProperties.Add("SessionKey", "ABCDEFG");
To get the value
var ccc = aaa.IncomingMessageProperties["SessionKey"];
That's it

I found that we miss the data or current context when we make async call with multiple thread switching. To handle such scenario you can try to use CallContext. It's supposed to be used in .NET remoting but it should also work in such scenario.
Set the data in the CallContext:
DataObject data = new DataObject() { RequestId = "1234" };
CallContext.SetData("DataSet", data);
Retrieving shared data from the CallContext:
var data = CallContext.GetData("DataSet") as DataObject;
// Shared data object has to implement ILogicalThreadAffinative
public class DataObject : ILogicalThreadAffinative
{
public string Message { get; set; }
public string Status { get; set; }
}
Why ILogicalThreadAffinative ?
When a remote method call is made to an object in another AppDomain,the current CallContext class generates a LogicalCallContext that travels along with the call to the remote location.
Only objects that expose the ILogicalThreadAffinative interface and are stored in the CallContext are propagated outside the AppDomain.

Related

How can I make an ASP Core Claims Principal available in a non-controller object?

I am working on an ASP Core 2 project using JWT authentication and the Dapper ORM.
Like all ASP projects, I have a lot of controllers, each instantiating its associated data objects. Each data object inherits from an abstract DbObject class that provides database access services. I also have an AuthenticatedUser object that abstracts the JWT to make it's properties easier to use.
What I want is to do is create the AuthenticatedUser object in the constructor of DbObject. Of course, one method is to create it in the controller and pass it to every concrete data object but this is messy as it would have to be passed hundreds of times (and it just feels wrong).
Is there a way to use the ASP Core middleware to get the token after authentication and make it available through dependency injection in the DbObject?
Edit
Hopefully, this clarifies my intentions. I would like the controller to create data objects and use their properties and methods without regard to implementation (i.e. DbObject). But queries executed by DbObject will be filtered by information in the token of the logged in user.
public class ManufacturerController : Controller {
[HttpGet]
public async Task<IActionResult> Get() {
var manufacturers = await new Manufacturer().SelectMany();
return Ok(manufacturers);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id) {
var manufacturer = await new Manufacturer().SelectOne(id);
return Ok(manufacturer);
}...
public class Manufacturer : DbObject<Manufacturer> {
protected override string QrySelectOne => #"
Select *
From org.fn_Manufacturers ({0})
Where Id = {1}";
protected override string QrySelectMany => #"
Select *
From org.fn_Manufacturers ({0})";
public int Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }...
public abstract class DbObject<T> {
protected readonly AuthenticatedUser authenticatedUser;
public DbObject(IHttpContextAccessor contextAccessor) {
authenticatedUser = new
AuthenticatedUser(contextAccessor.HttpContext.User);
}
protected abstract string QrySelectOne { get; }
protected abstract string QrySelectMany { get; }
public async Task<T> SelectOne (int id) {...}
public async Task<T> SelectOne(params object[] ids) {...}
public async Task<IEnumerable<T>> SelectMany () {...}
public async Task<IEnumerable<T>> SelectMany (params object[] ids) {...}
I suppose one solution may be to create a static data object factory which has the IHttpContextAccessor injected??
ASP.NET Core provides IHttpContextAccessor interface for accessing HttpContext from non-controller objects.
The usage is fair simple. Inject IHttpContextAccessor into DbObject and access HttpContext by calling IHttpContextAccessor.HttpContext:
public abstract class DbObject
{
protected DbObject(IHttpContextAccessor contextAccessor)
{
var context = contextAccessor.HttpContext;
// Create instance of AuthenticatedUser based on context.User or other request data
}
}
EDIT
Your controllers instantiate data objects directly (with new operator), that's why you can't have IHttpContextAccessor injected out of the box. Here are possible solutions. I list them in order of my preference (from best to worst).
If each controller uses only one (or just several) types of data objects, the best options will be to avoid direct instantiation and move toward normal Dependency Injection.
So if ManufacturerController requires only Manufacturer like in your sample then, it's better to inject Manufacturer instance to controller, not to create it inside:
public class Manufacturer1Controller : Controller
{
private readonly Manufacturer manufacturer;
public Manufacturer1Controller(Manufacturer manufacturer)
{
this.manufacturer = manufacturer ?? throw new ArgumentNullException(nameof(manufacturer));
}
[HttpGet]
public async Task<IActionResult> Get()
{
var manufacturers = await manufacturer.SelectMany();
return Ok(manufacturers);
}
// ...
}
IHttpContextAccessor will be injected into Manufacturer and passed to base DbObject:
public class Manufacturer : DbObject<Manufacturer>
{
public Manufacturer(IHttpContextAccessor contextAccessor) : base(contextAccessor)
{
}
}
It's the cleanest solution in the list. You use DI in classic way and utilize all benefits DI provides.
If one controller could use dozens of different data objects, you could inject the factory object that creates instances of data objects. It could be simple implementation based on IServiceProvider:
public interface IDbObjectFactory
{
TDbObject Create<TDbObject>() where TDbObject : DbObject<TDbObject>;
}
public class DbObjectFactory : IDbObjectFactory
{
private readonly IServiceProvider serviceProvider;
public DbObjectFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public TDbObject Create<TDbObject>() where TDbObject : DbObject<TDbObject>
{
return serviceProvider.GetRequiredService<TDbObject>();
}
}
public class Manufacturer2Controller : Controller
{
private readonly IDbObjectFactory dbObjectFactory;
public Manufacturer2Controller(IDbObjectFactory dbObjectFactory)
{
this.dbObjectFactory = dbObjectFactory ?? throw new ArgumentNullException(nameof(dbObjectFactory));
}
[HttpGet]
public async Task<IActionResult> Get()
{
var manufacturer = dbObjectFactory.Create<Manufacturer>();
var manufacturers = await manufacturer.SelectMany();
return Ok(manufacturers);
}
}
The code for Manufacturer and DbObject does not change comparing to the first option.
I don't see any reason not to use option #1 or #2. However just to complete the picture, I'll describe another two options.
Inject IHttpContextAccessor into conroller and pass this instance (or IHttpContextAccessor.HttpContext.User) to Data Object constructor invoked with operator new:
public class Manufacturer3Controller : Controller
{
private readonly IHttpContextAccessor contextAccessor;
public Manufacturer3Controller(IHttpContextAccessor contextAccessor)
{
this.contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
}
[HttpGet]
public async Task<IActionResult> Get()
{
var manufacturer = await new Manufacturer(contextAccessor).SelectMany();
// or
// var manufacturer = await new Manufacturer(contextAccessor.HttpContext.User).SelectMany();
return Ok(manufacturer);
}
}
It's a bad solution, because you don't use Dependency Injection for Manufacturer here and loose many advantages that DI provides.
And the worst option would be using of static object factory with injected IHttpContextAccessor. With this approach you also loose benefits of DI. In addition you get ugly code somewhere in Startup that initializes static instance of IHttpContextAccessor. When you come to this approach, you'll discover that theere is no quite elegant way to do this.
My advice: use option #1 untill you have good reasons against it. Then use option #2.
Here is Sample Project on GitHub with samples for approaches ##1-3.

HttpContext.Items vs Scoped Service

Which is the better way to carry request data(Is there any difference between two way)?
For example:
Option 1(Scoped Service):
//Scoped Service(this may be interface)
public class SampleScopedService
{
public string Data { get; set; }
}
//Register service
services.AddScoped<SampleScopedService>();
//Set and Get Data
public class SampleUsage
{
private readonly SampleScopedService _sampleScopedService;
public SampleUsage(SampleScopedService sampleScopedService)
{
_sampleScopedService = sampleScopedService;
// _sampleScopedService.Data = "Sample";
// _sampleScopedService.Data
}
}
Option 2(HttpContext.Items)
//Scoped Service
public class SampleScopedService
{
private readonly IHttpContextAccessor _accessor;
public SampleScopedService(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public string GetData()
{
return (string)_accessor.HttpContext.Items["Data"];
}
}
//Register service
services.AddScoped<SampleScopedService>();
//Set Data
HttpContext.Items[“Data”] = ”Sample”;
//Get Data
public class SampleUsage
{
private readonly SampleScopedService _sampleScopedService;
public SampleUsage(SampleScopedService sampleScopedService)
{
_sampleScopedService = sampleScopedService;
//_sampleScopedService.GetData();
}
}
According to docs:
Avoid storing data and configuration directly in DI. For example, a
user’s shopping cart shouldn’t typically be added to the services
container. Configuration should use the Options Model. Similarly,
avoid “data holder” objects that only exist to allow access to some
other object. It’s better to request the actual item needed via DI, if
possible.
Since Options 1 is example of “data holder”, as far as possible we should avoid it.
Furthermore, Options 1 may cause Captive Dependency if you don't pay attention.
So using Option 2 with singleton lifetime is better way than using Option 1.

site wide variables per user

I have an MVC4 site that needs to maintain some information while (and ONLY while) the user is logged in. For example, once the user logs in, I get a 'user token' back that allows me access to several off site services.
I've tried two different approaches. The first was to use a public static class that accesses the user session. However, after reading up on static classes, I'm hesitant to use them. According to what I'm reading, static classes should only be used for read only objects, and I wasn't using it that way. Although the site site did seem to be working fine with a limited number of users (currently there's 10).
(If someone would like to explain to me why this is a bad idea in MVC4, please tell me and/or link to an article)
public class SessionAccessorClasses
{
public const string SessionAccessorSessionVariablesString = "_SessionAccessorSessionVariables";
public static SessionAccessorModel SessionVariables
{
get { return System.Web.HttpContext.Current.Session != null ? (SessionAccessorModel)System.Web.HttpContext.Current.Session[SessionAccessorSessionVariablesString] : null; }
set { System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString, value); }
}
}
My second (and current) approach is to use Session variables and access them using a globally available class.
public class SessionAccessorClasses
{
private const string SessionAccessorSessionVariablesString = "_SessionAccessorSessionVariables";
public SessionAccessorModel GetSessionVariables()
{
return System.Web.HttpContext.Current.Session != null ? (SessionAccessorModel)System.Web.HttpContext.Current.Session[SessionAccessorSessionVariablesString] : null;
}
public void SetSessionVariables(SessionAccessorModel value)
{
System.Web.HttpContext.Current.Session.Add(SessionAccessorSessionVariablesString, value);
}
public void ClearSessionVariables()
{
System.Web.HttpContext.Current.Session.Remove(SessionAccessorSessionVariablesString);
}
}
This works fine, but I hesitate to call it good is because I don't fully understand why the public static class was such a bad idea, and because I now have to instantiate my new class at the beginning of nearly every function, and call the Set/Update function at the end of every function; which feels wrong somehow.
So first, since my original static class was accessing the users session, is it really that bad?
Second, is my second class a more appropriate way of doing things? Can you suggest improvements?
Third, if nothing else, can you give me the positive/negative aspects of doing it either way?
You want to use Session in ASP.net. It was created for the purpose you describe.
ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests. ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. By default, ASP.NET session state is enabled for all ASP.NET applications.
I'm a fan of strongly-typed reusable session variables, so I wrote the following extensions to store whatever variables you want to create without the need to constantly remember magic strings.
public static class SessionExtensions
{
public static bool TryGetValue<T>(this HttpSessionStateBase session, out T value)
where T : class
{
var name = typeof(T).FullName;
value = session[name] as T;
var result = value != null;
return result;
}
public static void SetValue<T>(this HttpSessionStateBase session, T value)
{
var name = typeof(T).FullName;
session[name] = value;
}
public static void RemoveValue<T>(this HttpSessionStateBase session)
{
var name = typeof(T).FullName;
session[name] = null;
}
public static bool ValueExists(this HttpSessionStateBase session, Type objectType)
{
var name = objectType.FullName;
var result = session[name] != null;
return result;
}
}
So if you have a class:
public MyClass
{
public int MyInt { get; set; }
}
You can store it by simply:
Session.SetValue(MyClass);
that needs to maintain some information while (and ONLY while) the user is logged in.
These methods could be updated a few ways to fulfill this requirement. Here is one way:
public static bool TryGetAuthenticatedValue<T>(this HttpSessionStateBase session,
out T value)
where T : class
{
value = null;
if (HttpContext.Current.User != null
&& HttpContext.Current.User.Identity != null
&& HttpContext.Current.User.IsAuthenticated)
{
var name = typeof(T).FullName;
value = session[name] as T;
}
var result = value != null;
return result;
}
I would also recommend that whatever classes you store in session, be serializable. That is to say it has a parameterless constructor and marked as [Serializable].

Register RavenDb using Autofac?

Can anyone guide me on how I could register RavenDB using Autofac?
builder.Register<DocumentStore>(.. what after that?
Here is a sample console program that illustrates not only how to wire up the document store, but also how to set it up so you can just inject your document session:
using System.Threading.Tasks;
using Autofac;
using Raven.Client;
using Raven.Client.Document;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
var builder = new ContainerBuilder();
// Register the document store as single instance,
// initializing it on first use.
builder.Register(x =>
{
var store = new DocumentStore { Url = "http://localhost:8080" };
store.Initialize();
return store;
})
.As<IDocumentStore>()
.SingleInstance();
// Register the session, opening a new session per lifetime scope.
builder.Register(x => x.Resolve<IDocumentStore>().OpenSession())
.As<IDocumentSession>()
.InstancePerLifetimeScope()
.OnRelease(x =>
{
// When the scope is released, save changes
// before disposing the session.
x.SaveChanges();
x.Dispose();
});
// Register other services as you see fit
builder.RegisterType<OrderService>().As<IOrderService>();
var container = builder.Build();
// Simulate some activity. 5 users are placing orders simultaneously.
Parallel.For(0, 5, i =>
{
// Each user gets their own scope. In the real world this would be
// a new inbound call, such as a web request, and you would let an
// autofac plugin create the scope rather than creating it manually.
using (var scope = container.BeginLifetimeScope())
{
// Let's do it. Again, in the real world you would just inject
// your service to something already wired up, like an MVC
// controller. Here, we will resolve the service manually.
var orderService = scope.Resolve<IOrderService>();
orderService.PlaceOrder();
}
});
}
}
// Define the order service
public interface IOrderService
{
void PlaceOrder();
}
public class OrderService : IOrderService
{
private readonly IDocumentSession _session;
// Note how the session is being constructor injected
public OrderService(IDocumentSession session)
{
_session = session;
}
public void PlaceOrder()
{
_session.Store(new Order { Description = "Stuff", Total = 100.00m });
// we don't have to call .SaveChanges() here because we are doing it
// globally for the lifetime scope of the session.
}
}
// Just a sample of something to save into raven.
public class Order
{
public string Id { get; set; }
public string Description { get; set; }
public decimal Total { get; set; }
}
}
Note that DocumentStore is single instance, but DocumentSession is instance per lifetime scope. For this sample, I am manually creating the lifetime scopes and doing it in parallel, simulating how 5 different users might be placing orders at the same time. They will each get their own session.
Putting SaveChanges in the OnRelease event is optional, but will save you from having to put it in every service.
In the real world, this might be a web application, or a service bus application, in which case your session should be scoped to either the single web request or the lifetime of the message, respectively.
If you are using ASP.Net WebApi, you should go get the Autofac.WebApi package off NuGet and use their .InstancePerApiRequest() method, which automatically creates the appropriate lifetime scope.

Ninject, Generic Referential Bindings

I think this falls under the concept of contextual binding, but the Ninject documentation, while very thorough, does not have any examples close enough to my current situation for me to really be certain. I'm still pretty confused.
I basically have classes that represent parameter structures for queries. For instance..
class CurrentUser {
string Email { get; set; }
}
And then an interface that represents its database retrieval (in the data layer)
class CurrentUserQuery : IQueryFor<CurrentUser> {
public CurrentUserQuery(ISession session) {
this.session = session;
}
public Member ExecuteQuery(CurrentUser parameters) {
var member = session.Query<Member>().Where(n => n.Email == CurrentUser.Email);
// validation logic
return member;
}
}
Now then, what I want to do is to establish a simple class that can take a given object and from it get the IQueryFor<T> class, construct it from my Ninject.IKernel (constructor parameter), and perform the ExecuteQuery method on it, passing through the given object.
The only way I have been able to do this was to basically do the following...
Bind<IQueryFor<CurrentUser>>().To<CurrentUserQuery>();
This solves the problem for that one query. But I anticipate there will be a great number of queries... so this method will become not only tedious, but also very prone to redundancy.
I was wondering if there is an inherit way in Ninject to incorporate this kind of behavior.
:-
In the end, my (ideal) way of using this would be ...
class HomeController : Controller {
public HomeController(ITransit transit) {
// injection of the transit service
}
public ActionResult CurrentMember() {
var member = transit.Send(new CurrentUser{ Email = User.Identity.Name });
}
}
Obviously that's not going to work right, since the Send method has no way of knowing the return type.
I've been dissecting Rhino Service Bus extensively and project Alexandria to try and make my light, light, lightweight implementation.
Update
I have been able to get a fairly desired result using .NET 4.0 dynamic objects, such as the following...
dynamic Send<T>(object message);
And then declaring my interface...
public interface IQueryFor<T,K>
{
K Execute(T message);
}
And then its use ...
public class TestCurrentMember
{
public string Email { get; set; }
}
public class TestCurrentMemberQuery : IConsumerFor<TestCurrentMember, Member>
{
private readonly ISession session;
public TestCurrentMemberQuery(ISession session) {
this.session = session;
}
public Member Execute(TestCurrentMember user)
{
// query the session for the current member
var member = session.Query<Member>()
.Where(n => n.Email == user.Email).SingleOrDefault();
return member;
}
}
And then in my Controller...
var member = Transit.Send<TestCurrentMemberQuery>(
new TestCurrentMember {
Email = User.Identity.Name
}
);
effectively using the <T> as my 'Hey, This is what implements the query parameters!'. It does work, but I feel pretty uncomfortable with it. Is this an inappropriate use of the dynamic function of .NET 4.0? Or is this more the reason why it exists in the first place?
Update (2)
For the sake of consistency and keeping this post relative to just the initial question, I'm opening up a different question for the dynamic issue.
Yes, you should be able to handle this with Ninject Conventions. I am just learning the Conventions part of Ninject, and the documentation is sparse; however, the source code for the Conventions extension is quite light and easy to read/navigate, also Remo Gloor is very helpful both here and on the mailing list.
The first thing I would try is a GenericBindingGenerator (changing the filters and scope as needed for your application):
internal class YourModule : NinjectModule
{
public override void Load()
{
Kernel.Scan(a => {
a.From(System.Reflection.Assembly.GetExecutingAssembly());
a.InTransientScope();
a.BindWith(new GenericBindingGenerator(typeof(IQueryFor<>)));
});
}
}
The heart of any BindingGenerator is this interface:
public interface IBindingGenerator
{
void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel);
}
The Default Binding Generator simply checks if the name of the class matches the name of the interface:
public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
{
if (!type.IsInterface && !type.IsAbstract)
{
Type service = type.GetInterface("I" + type.Name, false);
if (service != null)
{
kernel.Bind(service).To(type).InScope(scopeCallback);
}
}
}
The GenericBindingGenerator takes a type as a constructor argument, and checks interfaces on classes scanned to see if the Generic definitions of those interfaces match the type passed into the constructor:
public GenericBindingGenerator(Type contractType)
{
if (!contractType.IsGenericType && !contractType.ContainsGenericParameters)
{
throw new ArgumentException("The contract must be an open generic type.", "contractType");
}
this._contractType = contractType;
}
public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
{
Type service = this.ResolveClosingInterface(type);
if (service != null)
{
kernel.Bind(service).To(type).InScope(scopeCallback);
}
}
public Type ResolveClosingInterface(Type targetType)
{
if (!targetType.IsInterface && !targetType.IsAbstract)
{
do
{
foreach (Type type in targetType.GetInterfaces())
{
if (type.IsGenericType && (type.GetGenericTypeDefinition() == this._contractType))
{
return type;
}
}
targetType = targetType.BaseType;
}
while (targetType != TypeOfObject);
}
return null;
}
So, when the Conventions extension scans the class CurrentUserQuery it will see the interface IQueryFor<CurrentUser>. The generic definition of that interface is IQueryFor<>, so it will match and that type should get registered for that interface.
Lastly, there is a RegexBindingGenerator. It tries to match interfaces of the classes scanned to a Regex given as a constructor argument. If you want to see the details of how that operates, you should be able to peruse the source code for it now.
Also, you should be able to write any implementation of IBindingGenerator that you may need, as the contract is quite simple.