PDA

View Full Version : Protection level problem when using Spring


diegoalvarez
04-20-2007, 10:29 PM
Hello all:

Working with Spring, I found an unusual behavior in a class access level, which is lost for internal classes:

The next example shows MyClass class, which has an internal access level (meaning that it's only accessible to members of the same assembly), but that can be used through Spring without restrictions from another assembly. If you try to accomplish this using just the .NET Framework, you'll get the expected error.

With spring:

using MyNamespace.Interfaces;
namespace MyNamespace.Logic
{
internal class MyClass : IInterface
{
public int MyMethod()
{
}
}
}

namespace MyNamespace.Interfaces
{
public interface IInterface
{
int MyMethod()
}
}


Here's the reference to the protected class from another assembly (App.config):


App.config --> Spring.NET
<objects xmlns="http://www.springframework.net">
<object name="MySpringObject" type="MyNamespace.Logic.MyClass , MyNamespace.Logic" singleton="false" />
</objects>


This piece of code executes without a problem, even though MyClass is internal:


namespace AnotherNamespace
{
public class Program
{
public static void Main(string[] args)
{
IInterface object = (IInterface)
ContextRegistry.GetContext()["MySpringObject"];

int i = object.MyMethod();
}
}
}


If you try to instance the class by using just the .NET Framework, you'll get a compile time error because of access level protection:


using MyNamespace.Logic;
namespace AnotherNamespace
{
public class Program
{
public static void Main(string[] args)
{
IInterface obj = new MyClass(); -- ERROR!!!!!!!!
}
}
}
ERROR = 'MyNamespace.Logic.MyClass' is inaccessible due to its protection level


The question is: Is this a bug, or was it made on purpose?

Bruno Baia
04-22-2007, 11:30 PM
Hi,

That's Dependency injection, when you do this :

IInterface object = (IInterface)ContextRegistry.GetContext()["MySpringObject"];

You retrieve an implementation of the interface 'IInterface' not necessarily a MyClass instance, and the interface is public.


- Bruno

diegoalvarez
04-24-2007, 12:32 AM
although the interface is public is accessing a internal class, I believe that it must not have access.

or where I am being mistaken?

Tks for your reply :-D

Erich Eichinger
04-24-2007, 05:54 AM
Hi,

you are right: Spring doesn't care about class visibility when instantiating a new object. This is for several reasons, legacy integration issues among them.

cheers,
Erich

tbroyer
04-24-2007, 05:31 PM
although the interface is public is accessing a internal class, I believe that it must not have access.

or where I am being mistaken?


Spring just uses .NET's built-in reflection facilities.

If you believe such a behavior is buggy, then tell Microsoft :p