roy barak
roy barak

Reputation: 53

Get an instance of class from one assembly at another assembly but at the same project

I writing a project that holds few class libraries. In the lower layer i have a class that look like this:

namespace firstclasslibrary
{

    public abstract class Base<T> where T :SomeClass
    {
            public static Base<T> Current 
            { 
                 get 
                 {
                       return new Base() ;
                 }
            }
    }
}

and then in a different class library i have:

namespace secondclasslibrary
{
      public class Derived : Base
      {
           ///some kind of singleton ....
      }
}

now at the first class library i have another class that use the abstract class like this:

namespace firstclasslibrary
{
      public class JustAClass
      {
            public Base<SomeClass> baseclass = baseclass.Current;


            ////do some other things.....
      }
}

if all the classes were under the same class library i was able to get the instance of the Derived , but since it is a different library i get null it doesn't get the instance i was created in the main project.

Is there a way to make it work?

Upvotes: 2

Views: 453

Answers (2)

Guffa
Guffa

Reputation: 700322

If the first library doesn't have a reference to the second library, then it doesn't know about the concrete implementation of the class, so it can't create an instance of it on its own.

You would have to tell the class how to create an instance, for example:

namespace firstclasslibrary {

  public abstract class Base {

    private static Base _current = null;

    public static Func<Base> CreateInstance;

    public static Base Current { 
      get {
        if (_current == null) {
          _current = CreateInstance();
        }
        return _current;
      }
    }

  }

}

Before using the Current property, you have to set the CreateInstance property, to "learn" the class how to create the instance:

Base.CreateInstance = () => new Derived();

You could also expand on this by making the _current property protected, so that the constructor of the Derived class can set itself as the current instance if you create an instance of the class instead of using the Current property.

Upvotes: 0

Z .
Z .

Reputation: 12837

You should be able to do what you are suggesting as long as the second class library has a reference to the first.

Upvotes: 1

Related Questions