I want to add an easily accessible helper class to my asp mvc page. I created a class called Repositories. It has a static property "Current" which does the following:
public static readonly Repositories Current
{
get
{
if(HttpContext.Current.Items["Repositories"] == null)
HttpContext.Current.Items["Repositories"] = new Repositories(HttpContext.Current);
return (Repositories)HttpContext.Current.Items["Repositories"];
}
}
The point is that the class has static helper functions that use the current instance of the class (tied to current httpcontext). The helper functions do all kinds of stuff, the reason I wanted to organize them like this is because it makes for a nicer looking code in the controllers and i have potential access to all database repositories (the actual handle objects are created only if accessed in this context though).
Anyway, as you can see, the constructor takes a HttpContext as an argument, which is then stored in a private class field so I'd have less to type. This means that the Repositories class instance refers to HttpContext class instance and vice-versa. When the HttpContext is dropped, does this mean that it still sticks around in the memory, being preserved by a circular-reference by the Repositories instance?
An "orphaned" circular reference doesn't force objects to stay around in memory.
If you do this:
class A
{
public B b;
~A()
{
Console.WriteLine("COLLECTED A!");
}
}
class B
{
public A a;
~B()
{
Console.WriteLine("COLLECTED B!");
}
}
and run this code:
var a = new A();
var b = new B();
a.b = b;
b.a = a;
a = null;
b = null;
GC.Collect();
Both instances can (and will) be garbage collected. You will get something similar to the following output:
COLLECTED B!
COLLECTED A!
Related
Can any one explain the reasons of Validity and Invalidity of following C# code:
class A
{
protected void ProtectedFunction()
{
A a = new A();
a.ProtectedFunction(); //Valid (Point 2)
}
}
class B : A
{
public void Function_B()
{
A a = new A();
base.ProtectedFunction();//Valid (Point 1)
a.ProtectedFunction(); //Invalid, why??? (Point 1)
B b = new B();
b.ProtectedFunction(); //Valid, called by instance b (Point 2)
ProtectedFunction(); //Valid, called by base instance
}
}
class C : B
{
public void Function_C()
{
A a = new A();
a.ProtectedFunction(); //Invalid, why??? (Point 1)
B b = new B();
b.ProtectedFunction(); //Invalid, why??? (Point 2)
C c = new C();
c.ProtectedFunction(); //Valid, called by instance c (Point 2)
ProtectedFunction(); //Valid, called by base instance
}
}
It seems like the instance in its own class/context can access the protected method but the same instance out of class/context cannot access the method.
The question is when accessing by instance, the code being executed is not in the instance own context but in another instance's context (though of same class).
Private = only this class can use.
Protected = only this class and derived classes can use.
with a = new A() you are creating an instance of a and accessing as an outsider so this method is not available.
If you want to access a member through an instance, it should be public (or internal if you only want to access from within the assembly)
These calls
A a = new A();
a.ProtectedFunction(); //Invalid, why??? (Point 1)
are all invalid because ProtectedFunction() is not accessible from outside the instance of a class. So even though you are calling it from an inherited class, you are calling a difference instance (or, object, if you like) so you can no longer access it.
A real world example to get your head around this might be emails. I can read my own private emails, but you can't read mine. If I have children they inherit from me the ability to read their own private emails - but they still can't read mine!
All Point 1s are invalid since a protected method can be called from the class where they are defined; or from child classes in case of inheritance; a protected method can not be called on instances.
But there is one exception, whenever an instance of a class is used inside the class definition, protected methods can be accessed; so Point 2s are valid.
I've read about pro's/cons of static but I'm not sure about how to do it in my case from a performance point of view.
I have a classA with different variables and also functions with timers:
class ClassA
{
// More vars...
private System.Timers.Timer _values;
public ClassA(IntPtr handle, String t)
{
_handle = handle;
_title = t;
CheckRoutineAndContinue();
}
Where CheckRoutineAndContinue is this:
private void CheckRoutineAndContinue()
{
_values= new System.Timers.Timer();
_values.Elapsed += delegate { Check(); };
_values.Interval = 200;
_values.AutoReset = false;
_values.Start();
}
private void Check()
{
if (_max> 5) StopCheck();
else
{
// Logic...
_max++;
}
private void StopCheck()
{
if (_values!= null)
{
_values.AutoReset = false;
_values.Enabled = false;
_values.Stop();
}
}
My question is: I will have multiple objects of ClassA. If I create an static method for CheckRoutineAndContinue() it will only be created once and I can pass it the parameters I need to work with, whereas if I have it in my class, I don't need to send variables of ClassA and will be created only once. The code executed by all ClassA objects will be the same, but each one has different values in variables.
Is this a good occasion to create an static method and pass all the variables via parameters around somehow so these functions is only created one, or is it recommended to have these functions in the same class even though they are going to be created everytime I create a new ClassA object?
Assuming testing is no big deal in this case.
I would assume an static method is better as functions will be created again everytime, but I'm not 100% plus I'm not sure if an static method can handle the timer properly as I need to start-stop it depending on the logic of the function inside the timer.
I don't see any real benefit to using static here. I don't agree that your performance would be improved; you would still be doing the same thing.
Generally, statics are used for two reasons: (1) you want something to be a singleton object (for example, the location of some data shared by the entire app; or (2) the method involved does not alter any state of the class and therefore marked as static because this somewhat optimizes the creation of the class instance in memory (in a very minor way).
Say I have
public class A {
public A(IFoo foo, B bar);
}
and
public class B {
public B(IFoo foo)
}
How would I set up bindings so that a new instance of IFoo is created for every A but the same instance of IFoo is injected into B that is injected to the A the B is injected to?
Effectively I would want to achieve
var foo = new Foo();
var b = new B(foo);
var a = new A(foo, b);
var foo2 = new Foo();
var b2 = new B(foo2);
var a2 = new A(foo2, b2);
Ideally the above would happen magically if I call
var a = Kernel.Get<A>();
assert(a.Foo == a.B.Foo)
I would start like the below which will not achieve this. I can't figure out how to set the binding constraints. Perhaps it is not possible or even desirable to do this.
Kernel.Bind<A>.ToSelf();
Kernel.Bind<IFoo>.To<Foo>();
Kernel.Bind<B>.ToSelf();
Generally speaking, you would use the "scope" feature of ninject:
https://github.com/ninject/ninject/wiki/Object-Scopes
Specific to your problem, you can use NamedScope, which is available in the NamedScope extension: https://github.com/ninject/ninject.extensions.namedscope:
private const string FooScopeName = "FooScope";
Kernel.Bind<IFoo>().To<Foo>()
.DefinesNamedScope(FooScopeName);
Kernel.Bind<A>().ToSelf()
.InNamedScope(FooScopeName);
Kernel.Bind<B>().ToSelf();
The effect of this is that all dependencies injected into an IFoo instance (and their dependencies and so on --> the whole object tree rooting in an IFoo instance) will get the same instance of A.
(Hint: Call scope might also be sufficient to address your problem, depending on how the object tree is built).
I tried with the below code, I got the output as 1000. I heard assigning object must share the reference instead of copying the entire object memory. Here the result is different.Can anyone help.
public aaaaa ad = new aaaaa();
static void Main(string[] args)
{
Program p = new Program();
p.fun1();
p.fun2();
}
public void fun1()
{
using(smallclass s = new smallclass())
{
s.j = 1000;
ad.fun1(s);
}
}
public void fun2()
{
ad.fun2();
}
public class aaaaa
{
public smallclass h = new smallclass();
public void fun1(smallclass d)
{
h = d;
}
public void fun2()
{
Console.WriteLine(h.j);
}
}
public class smallclass:IDisposable
{
public int j = 9;
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
Update:
I expect an object reference exception as the referenced memory is disposed in p.fun1();
Here is an simple example how assinging works
using System;
namespace ConsoleApplication1
{
internal class Program
{
private static smallclass objA = new smallclass();
private static smallclass objB = new smallclass();
private static void Main(string[] args)
{
showValues();
objA.value = 1000;
showValues();
objB = objA;
showValues();
objA.value = 1055;
showValues();
}
private static void showValues()
{
Console.WriteLine("objA.value: " + objA.value);
Console.WriteLine("objB.value: " + objB.value);
Console.ReadLine();
}
}
internal class smallclass : IDisposable
{
public int value = 0;
public void Dispose()
{
//Here you can remove eventHandlers
//or do some other stuff before the GC will play with it
}
}
}
Like you can see
first we create 2 objects objA and objB
than we show the values like expected they are both 0
after that we increase the value of objA to 1000
the value of objA a is 1000 and the value of objB remains at 0
NOW we assingning objA and objB
so the value of objB got also 1000
if we now change the value of objA to 1055
the value of objB get also changed
because objB is no more an separate object it now holds the same
reference like objA does
EDIT
And now i will show you how you get your Error based on your example
change your aaaaa class to:
public class aaaaa
{
public WeakReference<smallclass> h;
public void fun1(smallclass d)
{
h = new WeakReference<smallclass>(d);
}
public void fun2()
{
smallclass k;
if(h.TryGetTarget(out k))
Console.WriteLine(k.j);
else
Console.WriteLine("ERROR ERRROR ERROR");
}
}
and modify your static void Main(string[] args) to:
static void Main(string[] args)
{
Program p = new Program();
p.fun1();
GC.Collect();
p.fun2();
Console.Read();
}
Ok lets get through the changes
we are using the WeakReference<T> (you could also use WeakReference)
if the GC now comes across our object he can't find a StrongReference so can Collect it
now to the GC.Collect() YOU need to call it because it forced the GC to do his work (now at this moment)
and remember like i told you before IDisposable will get called from the GC before he destroys the object (AFAIK) so there is the place to put all the stuff that need to be done before the object will get destroyed
No, assingning is not a "new" statement, it copies.... a reference, it does not create a new object. For a class.
For a struct, it does so.
I suggest learning C# by reading the documentation or a book - those basics are normally handled to great detail in those.
You will not go far wrong if you think of every reference type variable, field, parameter, array slot, or other such storage location, has holding either "null", or "object #24601" [or some other number]. There are really only a handful things that can be done with references:
You may create a null reference
You may ask the system to create a new object and return a reference to it
You may copy one reference to another
You may check whether two references are equal to each other, or whether one is equal to null.
You may ask the system to perform some action upon the object identified by a reference
If myCar is a variable of some reference type, a statement like myCar.Color = CarColors.Blue won't affect the variable myCar at all. Instead, it will observe that myCar holds [e.g.] "Object #8675309", and then ask the system to access the Color property or field of object #8675309. Conversely, if otherCar happens to hold "object #90210", a statement of the form otherCar=myCar won't do anything with object #8675309, nor object #90210, but will instead replace the "90210" stored in otherCar with "8675309".
Objects are guaranteed to exist as long as any form of reference to them exists, but if there are two objects which, although referenced by each other, are not referenced by anything else in the universe, both objects may simultaneously cease to exist. This rule is absolute, but there are a couple of twists: code may request a WeakReference to an object; an object is guaranteed to exist as long as a weak reference to it exists, but if the system discovers that no strong references to an object exist, it will invalidate every WeakReference to it. Further, the system keeps a list of all objects that have would like to be notified if they are abandoned. If the system finds that this list holds the only reference to an object, it will move the object to a strongly-referenced list of objects whose Finalize method should run at the first convenient opportunity. When the object's Finalize method is run, the reference will be removed from that latter list. If no reference to the object has been stored anywhere in the mean time, the object will cease to exist.
I have replaced GC.SuppressFinalize with GC.Collect() in dispose function, however this is not freeing the memory.. and am receiving 1000 as a result.
I guess, as it holds other reference(the variable h), GC will not free the memory, even if we invoked it explicit.
So we can very well pass and assign the objects irrespective of the allocated(new) object going out of scope.
Please correct me If i am wrong.
I have a class A maintaining a list of objects class B.
But each object of class B can be referenced in any object of class A.
Class B also maintains a list of objects of class A where it is being referenced.
The program can and will create (several) objects of both class A and B 'at will' and also delete them.
If I use C# I can add and delete objects from both classes with following code
public class A
{
private List<B>ListOfObjects_B;
public bool Add(B Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_B.IndexOf(B) <0))
{
ListOfObjects_B.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(B Object)
{
bool bDeleted = ListOfObjects_B.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
public class B
{
private List<A>ListOfObjects_A;
public bool Add(A Object)
{
bool bAdd = false;
if ((Object != null) && (ListOfObjects_A.IndexOf(A) <0))
{
ListOfObjects_A.Add(Object);
Object.Add(this);
bAdded = true;
}
return bAdded;
}
public bool Delete(A Object)
{
bool bDeleted = ListOfObjects_A.Remove(Object);
if (bDeleted == true) Object.Delete(this);
return bDeleted;
}
}
This will work as because of removing/adding the object to the ListOfObjects the SECOND time (by recursion) the function will be called it will fail to delete/add thereby avoiding an infinite loop.
But I don't like this code even though A and B do not know 'much' about the other class and just call a Delete/Add function.
I suppose this kind of problem is general and a design pattern exists for handling it in such a way that recursion can be avoided and updating both lists will be 'just better'.
What design pattern should I use? I would appreciate if some code would be added as well.
You can simplify thing by moving the "object association concern" into a dedicated class. Here's what I have in mind.
Define a class called AssociationTable. This class will maintain a list of pairs where each pair holds a reference to an A object and a reference to a B object.
Each A object (and each B object) will hold a reference to the AssociationTable object.
A.Add(B) will be implemented as table.add(this, b);
B.Add(A) will be implemented as table.add(a, this);
Deletion will be implemented as table.delete(this, b) or table.delete(a, this)
class Pair {
A a; B b;
Pair(A a, B b) { this.a = a; this.b = b; }
// Also override Equals(), HashCode()
}
class AssociationTalbe {
Set<Pair> pairs = ...;
void add(A a, B b) { pairs.add(new Pair(a, b)); }
void remove(A a, B b) { pairs.remove(new Pair(a, b)); }
}
class A {
AssociationTable table;
public A(AssociationTable t) { table = t; }
void add(B b) { table.add(this, b); }
void remove(B b) { table.remove(this, b); }
}
Edit:
The problem with this design is garbage collection. the table will hold references to objects thereby supressing their collection. In Java you could use a WeakReference object to overcome this issue. I am pretty sure there's something similar in the .Net world
Also, the table could be a singleton. I don't like singletons too much. In here, a singleton will make the A-B association unique across your program. This may be something that is undesirable but it depends on your concrete needs.
Finally, (just to put things in context) this design works the same way as Many-to-Many relationships in relational data bases.
I recently wrote a class to handle a similar problem. It is actually a simpler scenario (parent/child relationship with the children referencing their parent), but you could probably adapt it for your needs. The main difference is that the Parent property in my implementation should be replaced by a collection of parents.
About the only thing I can think of is using a Mediator pattern so that A doesn't add itself to B. Here's an example:
public class Mediator {
public void Add(A List, B Object) {
if(list.Add(Object)) {
object.Add(List);
}
}
public void Delete(A List, B Object) {
if(List.Delete(Object)) {
Object.Delete(List);
}
}
}
After this you would remove the lines of code which read "Object.Add(this);" and "if (bDeleted == true) Object.Delete(this);" This also has the benefit of reducing how many times each method is called as before object A's methods were being called twice since object B was also calling those methods on object A.
EDIT: Upon further review, I realized you were already using an Observer design pattern in a way. Object A is the observer and object B is the observable. Object A maintains a list of objects its observing and object B maintains a list of objects observing it. The only thing is I don't see any additional functionality, although there probably is some. Basically, Object B will notify all Object A's observing it that it's changed and all of those Object A's will ask for the change. If this is what you're looking for, then all you need to do is remove the lines "Object.Add(this);" and "if(bDeleted == true) Object.Delete(this);" from the B code as it is unnecessary.