Detect duration of layer
This YouTube tutorial explains how to do this:
After Effects Quick Tip - How to Add Auto Opacity To Layers and Footage


Add an expression to the layer's Opacity property by alt-clicking the stopwatch.
Paste this expression into the box:

fadeDuration = .5;
Math.min(linear(time,inPoint,inPoint + fadeDuration, 0, 100), linear(time,outPoint - fadeDuration,outPoint,100,0))

The layer will now fade in for half a second, and then fade out for half a second based on its in and out points.
If want to specify the length in frames instead of seconds, change the first line of the expression to be this:
fadeDuration = thisComp.frameDuration * 5;

Now the layer will fade in and fade out over a period of 5 frames.