why a protectd method of a class can nor be accessed by creating its object in sub class? - c#-2.0

i have a code like this, but giving error can not access protected member.
**Class A
{
protected void m1()
{
some code
}
}
Class B:A
{
B b=new B();
b.m1();// Ok works fine
A a =new a();
a.m1();/// don't work, compile time error
A a2=new B();
a2.m1(); //compile time error, don't work
}**
just not getting reason behind this, Why so aberrant nature of the above code, why a method of a class using same class object not accessible out side. While i searched a bit for this but did not undersand, i found something that compiler nature come in picture, but i did not understand.

you can prefix your call by base keyword for calling base members. protected means that a member could be inherited by descendants and could be called but through the specified way.
calling a.m1() in your class hasn't any difference with calling it form an out of B code.

As stated above, the protected method inside the class can only be accessed by the class that inherits the original container.In your case B is the sub class, a is your base. Inside your B class you are creating a new instance of A class ('a'), and this is now a different object (B class does not care about this new object A). This new object 'a' will not expose the protected method, so 'a.m1()' will throw a compile error.

Related

How can I inject a custom service not associated with any domain class in grails?

I wish to make DAO layer in my grails project which would be not be associated with any of the domain classes and would be interacting with the secondary database of my project. I get the following error when I try to inject the service in any controller:
"Cannot invoke method abc() on null object"
However, the error is resolved and works perfectly when I initialise the service using the new keyword in the controller but I know that shouldn't be necessary as grails is supposed to handle it. Can anyone tell me what am I missing?
I don't think the issue has anything to do with whether or not the service is associated with a domain class. The DI container doesn't know anything about that.
If you have a controller like this:
// grails-app/controllers/demo/SomeController.groovy
package demo
class SomeController {
SomeService someService
def someControllerAction() {
someService.abc()
// ...
}
}
And a service like this...
// grails-app/services/demo/SomeService.groovy
package demo
class SomeService {
void abc() {
// ...
}
}
That will work fine.
It is almost impossible to say for sure without seeing what your code what you are doing wrong but one possibility is something like this, which will not work:
// grails-app/controllers/demo/SomeController.groovy
package demo
class SomeController {
def someControllerAction() {
// This is a local variable, not
// a property and as such will not
// be subjected to dependency injection.
SomeService someService
// ...
someService.abc()
// ...
}
}
Also, make sure the property name (someService in the sample above) matches the service class name, but with a lower case first letter (more generally, make sure the property name matches the property name representation of the service class name, which is usually as simple as lower casing the first letter of the class name).

Ninject is reusing instances which are explicitly defined InTransientScope()

I am experiencing an issue, and I have come to a dead end on how to debug and resolve this.
I have an MVC application which is using Ninject for IoC and DI.
One of my dependencies is IApplicationLogger which I am currently implementing using Log4Net.
In my NinjectWebCommon I am binding my IApplicationLogger as follows:
kernel.Bind<IApplicationLogger>()
.ToMethod(ctx =>
{
string configFile = System.Configuration.ConfigurationManager.AppSettings["log4netconfigfilelocation"];
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(HttpContext.Current.Server.MapPath(configFile)));
var name = ctx.Request.Target.Member.DeclaringType.FullName;
var log4Netlogger = log4net.LogManager.GetLogger(name);
return new Log4NetApplicationLogger(log4Netlogger);
}).InTransientScope();
All fairly straight forward stuff.
However, I am finding that the first instance of IApplicationLogger which is activated is then passed to all constructors which require an IApplicationLogger instance.
for example I have the following
public class A : IA
{
public A(IB bclass, IC cclass, IApplicationLogger logger){}
}
public class B : IB
{
public B(IApplicationLogger logger){}
}
public class C : IC
{
public C(IApplicationLogger logger){}
}
I have set breakpoints on each constructor and also the line in my NinjectWebCommon kernel.Bind().ToMethod(ctx =>
What I see is this:
Break point in NinjectWebCommon is hit, and I can see
ctx.Request.Target.Member.DeclaringType.FullName is Class B.
Break point in Constructor Class B is hit and logger
instance is correct
Break point in Constructor Class C is hit, and
logger instance has a logger name of Type Class B
Break point in Constructor Class A is hit, and logger instance has a logger
name of Class B
I would expect the breakpoint within NinjectWebCommon to be hit for each new instance of IApplicationLogger that is required, but it is only hit once for the first activation for the instance of Class B.
I have tried my Binding without the InTransientScope() option.
My IA, IB and IC bindings are defined InSingletonScope(). This shouldn't cause an issue as I am expecting Ninject to activate an instance of each, each with it's own instance of IApplicationLogger.
The result of the binding I am seeing currently is that logging statements I output in say Class A are being recorded in the Log as being from a logger name for class of type B.
Can anyone suggest how I can diagnose why Ninject is reusing the TransientScoped() IApplicationLogger, or how I can peek under the hood of what Ninject is doing so that I can analyse this in greater detail?
For anyone interested I didn't discover the underlying issue here, but I have opted to inject an ILoggerFactory with a single method .GetLogger(string typename), allowing my classes to request their own Logger and passing their own Type name.
This way I can ensure that each Class has it's own logger, with the LoggerName matching the Class TypeName.

I want ClassA to get particular a particular instance of ClassB, but can't modify either class directly

Say I have two JdbcTemplates, one for "employee_database" and one for "customer_database". Say a class EmployeeDAO requires the former as a constructor dependency, and CustomerDAO requires the latter. If I were writing these classes myself, I'd do
public class EmployeeDAO {
public EmployeeDAO(#Named("employee") JdbcTemplate employeeJdbcTemplate)
and
bind(JdbcTemplate.class).annotatedWith(Names.named("employee")).toInstance(employeeJdbcTemplateInstance);
And likewise for CustomerDAO
But I can't modify EmployeeDAO to add the Named annotation to the constructor parameters.
What's the canonical way to insure the DAO objects get their respective JdbcTemplates in this scenario without having to instantiate them myself?
In a sense, this is similar to the "robot legs problem", as you're trying to create similar-but-slightly-different trees of objects. In the eponymous problem, you're using a reusable Leg object that receives a #Left Foot and a #Right Foot as needed; in this problem, you're similarly varying the binding of an inner object (JdbcTemplate) based on an outer object's (DAO's) context.
A "cheap way" is to use #Provides methods, which is a particularly low-cost solution if your consumer DAOs have few dependencies and are unlikely to change frequently. Naturally, creating a full Provider would also work too, but this syntax works just fine for most cases.
public class YourModule extends AbstractModule {
#Override public void configure() {}
#Provides EmployeeDao createEmployeeDao( // Name doesn't matter.
#Named("employeeJdbcTemplate") JdbcTemplate employeeTemplate,
Dep2 dep2,
Provider<Dep3> dep3Provider) {
return new EmployeeDao(employeeTemplate, dep2, dep3Provider);
}
}
If the dep list is long, deps change frequently, or multiple classes depend on a JdbcTemplate, then private modules may be the way to go.
install(new PrivateModule() {
#Override public void configure() {
bind(JdbcTemplate.class).toInstance(employeeJdbcTemplate);
expose(EmployeeDao.class);
}
});
The example above uses an anonymous inner class, but you could also create a named class (either top-level or nested) that accepts a JdbcTemplate instance and a DAO class literal, and call it like so:
install(new DaoModule(employeeTemplate, EmployeeDao.class));
install(new DaoModule(customerTemplate, CustomerDao.class));

The sequence of ModelDriven and Prepare?

I put the println() in each method of Action class.
public String execute() throws Exception {
System.out.println("execute");
//...
}
public void prepare() throws Exception {
System.out.println("prepare");
//...
}
public Object getModel() {
System.out.print("getModel");
//...
}
I thought the order would be;
prepare → execute → getModel.
Because I remember I read it in the book, so I used to construct beans class and do some logics in prepare(), and just return SUCCESS in execute().
And I think getModel is for pushing the bean to the valueStack, right?
...anyway the console showed me this. It's very weird;
prepare → getModel → execute.
And this is becoming a huge problem to me. It's very hard to explain the reason in English... but I'll try!
I used to create each action class which is dealing with same beans, and of course there are same codes(variables, and their getters and setters) duplicated in each action class.
Now I'm trying to create one action to avoid that duplication. This action class has several methods(mapped in struts.xml like this;<action name="View_board" method="view">).
And as we saw in the console, this view() is called at the last in the action class like execute(). The prepare() does only construct beans, and the view() does real jobs. But getModel() is called before calling of view(), so there's no chance to put the beans to ValueStack.
I hope you guys understand what I'm trying to explain.
To sum it up, there are each action class like BoardView, BoardDelete, BoardWrite... and they worked well! But I hate that duplicated things so I created BoardManager class. This class has each method(like view()) which was handled by class(like BoardView). But this view() was called after the call of getModel(), so the bean(return of getModel()) has no chance to be pushed to the ValueStack.
Please help me out. Teach me your know-how in the field. I'm developing it all on my own and this is making me feel so hard.
Thank you!!
You have to set the Model object yourself as the modeldriven interceptor can only push it to the stack if its not null. If your getModel() looks like this:
SomeModelClass myModelObject = null;
public Object getModel()
{
return myModelObject;
}
... you'll have to set the modelObject so it can get pushed to the valueStack. You could do it this way I guess:
public void prepare(){
myModelObject = new myModelObject("I'm so new");
}
... or just initialize it in the field:
SomeModelClass myModelObject = new myModelObject("I'm so new");
Don't forget to implement the appropriate Interfaces (ModelDriven and Preparable). Hope this helps a bit.
I found my own solution.. but not a good one..
When setting domain object by setter, I push it to the valuestack manually..
It works good and only 2 lines added to my class.
But I don't feel that good.

How to inject with Guice when there are two different constructors?

Total Guice noob here, have read a few articles and seen the intro video, that's about it.
Here's my simplified old code that I'm trying to "guicifiy". Can't quite figure out how to, since (as far as I understand), I can only #inject-annotate one of the two constructors? How can a calling class create the one or the other instance? Or will I have to refactor this somehow?
public class MyDialog extends JDialog {
public MyDialog( JFrame parent, <other parameters...> ) {
super( parent );
}
public MyDialog( JDialog parent, <other parameters...>) {
super( parent );
}
}
You can only inject into the one ctor.
Depending on how this class is being used, you could:
Inject a factory into the client code with two "new" methods.
Roll all the arguments into one ctor and pass null when not required.
How can a calling class create the one or the other instance?
This suggests that the calling classes will want multiple instances of MyDialog? Then you need to use a hand-rolled factory (Assisted Inject can handle this for you if you only had one ctor). I don't know the details of what you are up to and I'm likely repeating what you already know but as a blanked statement I'd suggest also extracting an interface from MyDialog and have the factory return them. This way you can fake MyDialog in tests.
Constructor injection is very clean. mlk is right, saying that you can inject into one constructor only.
What you can do is use method injection:
public class Smt {
private int a;
private Cereal cereal;
private Personality personality;
private ignition;
public Smt() {
this.a = 5;
}
public Smt(int a) {
this.a = a;
}
#Inject
public void setup(#CiniMini Cereal cereal, #Rastafarian Personality personality,
Ignition ignition) {
this.cereal = cereal;
this.personality = personality;
this.ignition = ignition;
}
}
What Guice will do is call your class' setup class method and provide all the injections. Then you do the same thing as in the constructor--assign the objects to your class' attributes.
I agree with the previous comments.
Just an additional hint: constructor injection is supposed to provide all dependencies a class needs. As mlk says, one approach could be to annotate the constructor with most arguments and then refactor the other one to call the former by passing null values where needed.
Additionally, Guice 3.0 supports the so called Constructor Bindings which allow the programmer to specify which constructor to use. See here for more details.

Resources